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

Add an option to generate TypeAlias for literals when using the `--enum-field-as-literal` #1285

Open mmohaveri opened 1 year ago

mmohaveri commented 1 year ago

Is your feature request related to a problem? Please describe.

Currently datamodel-code-generator has an option to parse enums as python's string literal (e.g. Literal["A", "B"]), this is great and I'm using it a lot, but the problem is if I want to pass these literal around in my code, I have to define their type once again. e.g:

MyLiterals: TypeAlias = Literal["A", "B"]

def my_func(l: MyLiterals): ...

This is in contrast with all other types and structures generated by datamodel-code-generator. For example if had chosen to use python enums, I would have a MyLiteral enum in the generated code and could have use it in the function's type hint.

Describe the solution you'd like I like to have an additional option in the CLI to tell datamodel-code-generator to create these literal definitions automatically.

Describe alternatives you've considered

Currently I just copy and paste the literals generated by datamodel-code-generator into a separate file and re-define them, which can be a little non-DRY.

mmohaveri commented 1 year ago

@koxudaxi Is this something that you agree with and plan to do? If so I may be able to send a PR for it if you haven't planed and worked on it yet

koxudaxi commented 1 year ago

@mmohaveri Thank you for creating the issue. I want the feature too. But, I don't have the time :( I'm happy if you create the PR.

mmohaveri commented 1 year ago

@koxudaxi Sure, I'll see what I can do and send a PR