Add logic to handle globalns and localns in pydantic_model_creator#1876
Open
alistairmaclean wants to merge 3 commits intotortoise:developfrom
Open
Add logic to handle globalns and localns in pydantic_model_creator#1876alistairmaclean wants to merge 3 commits intotortoise:developfrom
globalns and localns in pydantic_model_creator#1876alistairmaclean wants to merge 3 commits intotortoise:developfrom
Conversation
907e457 to
8214c73
Compare
8214c73 to
f47dec6
Compare
CodSpeed Performance ReportMerging #1876 will not alter performanceComparing Summary
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 definedAs 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_creatorof my fork.Checklist: