Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Imports break when schema files are named the same as a schema defined within them #1896

Open
AniketDas-Tekky opened this issue Mar 29, 2024 · 0 comments

Comments

@AniketDas-Tekky
Copy link

AniketDas-Tekky commented Mar 29, 2024

Describe the bug
I have a directory of json schemas that cannot be modified. Inside this directory, there are several files with the following layout:

// Foo.json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Foo",
  // ...
}

// Bar.json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Bar",
  "properties": {
    "foo": {
      "$ref": "./Foo.json"
    }
}

This results in a generated directory that looks like

Foo.py
Bar.py

A Foo.py that looks like

class Foo(BaseModel):
    # ...

And a Bar.py that looks like

from . import Foo

class Bar(BaseModel):
    foo: Optional[Foo] = None

I then package this module and publish it on a private repo. When I try to use it in another project, I get the following error

TypeError: typing.Optional requires a single type. Got <module 'Foo'> from '...'

I believe this error happens because the module and class have the same name. If i try again, but rename the module to Foo2.py, then the genereated Bar.py looks like

from . import Foo2

class Bar(BaseModel):
    foo: Optional[Foo2.Foo] = None

And there's no error

Expected behavior
The Foo class should be used for typing instead of the Foo module.

Version:

  • OS: Mac OSX Sonoma 14.4
  • Python version: 3.9
  • datamodel-code-generator version: 0.25.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant