Skip to content

Commit

Permalink
Fix an exact import bug with deeper nesting (#2089)
Browse files Browse the repository at this point in the history
* Fix an exact import bug with depper nesting

If a schema heirarchy was deeper than 1 level and a schema referenced
another schema at a higher level, then the exact import function would
add an extra '.'.
This change checks if `from_` is any number of '.' and prepends it
to the `import_` to maintain correct heirarchy.

* Removed an errant comment line

---------

Co-authored-by: Koudai Aono <koxudaxi@gmail.com>
  • Loading branch information
AniketDas-Tekky and koxudaxi authored Sep 27, 2024
1 parent 295b758 commit 8291eed
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 3 deletions.
5 changes: 3 additions & 2 deletions datamodel_code_generator/parser/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,11 @@ def relative(current_module: str, reference: str) -> Tuple[str, str]:


def exact_import(from_: str, import_: str, short_name: str) -> Tuple[str, str]:
if from_ == '.':
if from_ == len(from_) * '.':
# Prevents "from . import foo" becoming "from ..foo import Foo"
# or "from .. import foo" becoming "from ...foo import Foo"
# when our imported module has the same parent
return f'.{import_}', short_name
return f'{from_}{import_}', short_name
return f'{from_}.{import_}', short_name


Expand Down
2 changes: 1 addition & 1 deletion docs/development-contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ $ cd datamodel-code-generator
$ curl -sSL https://install.python-poetry.org | python3 -

## 3. Install dependencies
$ poetry install
$ poetry install --all-extras

## 4. Create new branch and rewrite code.
$ git checkout -b new-branch
Expand Down
1 change: 1 addition & 0 deletions tests/parser/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ def test_relative(current_module: str, reference: str, val: Tuple[str, str]):
'from_,import_,name,val',
[
('.', 'mod', 'Foo', ('.mod', 'Foo')),
('..', 'mod', 'Foo', ('..mod', 'Foo')),
('.a', 'mod', 'Foo', ('.a.mod', 'Foo')),
('..a', 'mod', 'Foo', ('..a.mod', 'Foo')),
('..a.b', 'mod', 'Foo', ('..a.b.mod', 'Foo')),
Expand Down

0 comments on commit 8291eed

Please sign in to comment.