koxudaxi / datamodel-code-generator

Pydantic model and dataclasses.dataclass generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.
https://koxudaxi.github.io/datamodel-code-generator/
MIT License
2.75k stars 301 forks source link

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

Open AniketDas-Tekky opened 7 months ago

AniketDas-Tekky commented 7 months ago

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:

AniketDas-Tekky commented 1 month ago

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