From 8291eeded910a8e331c09cbeb8e5ae70522769ff Mon Sep 17 00:00:00 2001 From: Aniket Das Date: Fri, 27 Sep 2024 00:44:54 -0700 Subject: [PATCH] Fix an exact import bug with deeper nesting (#2089) * 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 --- datamodel_code_generator/parser/base.py | 5 +++-- docs/development-contributing.md | 2 +- tests/parser/test_base.py | 1 + 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/datamodel_code_generator/parser/base.py b/datamodel_code_generator/parser/base.py index b4d1ec810..cb5ad4996 100644 --- a/datamodel_code_generator/parser/base.py +++ b/datamodel_code_generator/parser/base.py @@ -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 diff --git a/docs/development-contributing.md b/docs/development-contributing.md index aed6f6b06..918441beb 100644 --- a/docs/development-contributing.md +++ b/docs/development-contributing.md @@ -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 diff --git a/tests/parser/test_base.py b/tests/parser/test_base.py index 17ec80970..83fdb46ea 100644 --- a/tests/parser/test_base.py +++ b/tests/parser/test_base.py @@ -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')),