Add logic to handle globalns
and localns
in pydantic_model_creator
#1876
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
When using typing.get_type_hints in Python 3.12, the get_type_hints method will not evaluate forward references unless the referenced objects are part of the objects module scope, or the references are specified in the globalns/localns argument of get_type_hints.
Motivation and Context
When the models are not in the same module, forward references can't be evaluated.
My project structure resembles:
Output:
NameError: name 'Event' is not defined
As a temporary fix, I've added this logic in
models/__init__.py
, which is not ideal:I propose a solution where users specify the globalns for typing.get_type_hints:
I might be missing something, or maybe there's a more elegant solution. I'm open to discussion and feedback.
How Has This Been Tested?
I have been able to generate pydantic models by specifying globalns
Dict[str, Type[Model]]
when usingpydantic_model_creator
of my fork.Checklist: