datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

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

Open AniketDas-Tekky opened this issue 1 year ago • 1 comments

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

AniketDas-Tekky avatar Mar 29 '24 23:03 AniketDas-Tekky

Bump on this. I'm using a fragile post processing script to fix the imports.

AniketDas-Tekky avatar Sep 11 '24 16:09 AniketDas-Tekky