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

Effect of target-python-version

Open enadeau opened this issue 2 years ago • 3 comments

Describe the bug The python target version argument seems to have no effect on using more modern typing from python

For example, targeting 3.11 will still give type that are written as List[int] instead of the more modern list[int]

To Reproduce

Example schema:

openapi: 3.0.0
components:
  schemas:
    User:
      type: object
      properties:
        names:
          type: array
          items:
            type: string

Used command line:

$ datamodel-codegen --input specification.yml --target-python-version 3.11

The results is

# generated by datamodel-codegen:
#   filename:  specification.yml
#   timestamp: 2023-08-30T20:49:24+00:00

from __future__ import annotations

from typing import List, Optional

from pydantic import BaseModel


class User(BaseModel):
    names: Optional[List[str]] = None

Expected behavior

I'd expect that the newest feature of python would be used and the output would be

# generated by datamodel-codegen:
#   filename:  specification.yml
#   timestamp: 2023-08-30T20:49:24+00:00

from __future__ import annotations

from pydantic import BaseModel


class User(BaseModel):
    names: list[str] | None = None

Version:

  • OS: Ubuntu 20.04.6 LTS
  • Python version: 3.11.4
  • datamodel-code-generator version: 0.21.4

Additional context

It might also be that this is the expected behavior, but in this case it would be good to improve the documentation, as it's not clear to me what this argument is supposed to do.

Thanks for your good work on this nice project!

enadeau avatar Aug 30 '23 20:08 enadeau

@enadeau Thank you for creating the issue. We need another option to use standard collections.

  --use-standard-collections
       Use standard collections for type hinting (list, dict)

as it's not clear to me what this argument is supposed to do.

It's good point . we should update the document about the behavior

koxudaxi avatar Oct 04 '23 17:10 koxudaxi

Adding --use-standard-collections changed Optional[List[str]] to Optional[list[str]] but not list[str] | None.

pjungermann avatar Nov 13 '23 19:11 pjungermann

@pjungermann for this I think the option you want is --use-union-operator

enadeau avatar Apr 07 '24 13:04 enadeau