-
Notifications
You must be signed in to change notification settings - Fork 22
Fix forward references and circular dependencies in Pydantic models #799
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rjurney
wants to merge
6
commits into
mitchelllisle:main
Choose a base branch
from
Graphlet-AI:fix-forward-references
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a39015d
Fix forward references and circular dependencies in Pydantic models
rjurney 5ecd6e4
Add integration test for Company/Ticker models with forward references
rjurney d37ecc1
Removed unwanted test file
rjurney a650735
Make pass pre-commit
rjurney a2c6b3d
Merge branch 'main' into fix-forward-references
rjurney ff1d38d
Merge branch 'main' into fix-forward-references
rjurney File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change | ||
|---|---|---|---|---|
|
|
@@ -12,8 +12,10 @@ | |||
| Annotated, | ||||
| Any, | ||||
| Dict, | ||||
| ForwardRef, | ||||
| Literal, | ||||
| Optional, | ||||
| Set, | ||||
| Type, | ||||
| Union, | ||||
| get_args, | ||||
|
|
@@ -31,6 +33,7 @@ | |||
| SecretBytes, | ||||
| SecretStr, | ||||
| ) | ||||
| from pydantic.errors import PydanticSchemaGenerationError, PydanticUndefinedAnnotation | ||||
| from pydantic.fields import ComputedFieldInfo, FieldInfo | ||||
| from pydantic.json_schema import JsonSchemaMode | ||||
|
|
||||
|
|
@@ -173,6 +176,7 @@ def create_json_spark_schema( | |||
| by_alias: bool = True, | ||||
| mode: JsonSchemaMode = 'validation', | ||||
| exclude_fields: bool = False, | ||||
| _visited_models: Optional[Set[Type[BaseModel]]] = None, | ||||
| ) -> Dict[str, Any]: | ||||
| """Generates a PySpark JSON compatible schema from the model fields. This operates similarly to | ||||
| `pydantic.BaseModel.model_json_schema()`. | ||||
|
|
@@ -184,6 +188,7 @@ def create_json_spark_schema( | |||
| mode (pydantic.json_schema.JsonSchemaMode): The mode in which to generate the schema. | ||||
| exclude_fields (bool): Indicates whether to exclude fields from the schema. Fields to be excluded should | ||||
| be annotated with `Field(exclude=True)` field attribute | ||||
| _visited_models: Internal parameter to track visited models and prevent infinite recursion | ||||
|
|
||||
| Returns: | ||||
| Dict[str, Any]: The generated PySpark JSON schema | ||||
|
|
@@ -192,7 +197,29 @@ def create_json_spark_schema( | |||
| raise TypeError('`model` must be of type `SparkModel` or `pydantic.BaseModel`') | ||||
|
|
||||
| if mode not in get_args(JsonSchemaMode): | ||||
| raise ValueError(f'`mode` must be one of {get_args(JsonSchemaMode)}') | ||||
| raise ValueError(f"`mode` must be one of {get_args(JsonSchemaMode)}") | ||||
|
|
||||
| # Initialize visited models set if not provided | ||||
| if _visited_models is None: | ||||
| _visited_models = set() | ||||
|
|
||||
| # Check for circular references | ||||
| if model in _visited_models: | ||||
| # Return a placeholder for circular references | ||||
| return {'type': 'struct', 'fields': []} | ||||
|
|
||||
| # Add current model to visited set | ||||
| _visited_models = _visited_models.copy() # Make a copy to avoid modifying the original | ||||
| _visited_models.add(model) | ||||
|
|
||||
| # Resolve forward references in the model before processing | ||||
| if hasattr(model, 'model_rebuild'): | ||||
| try: | ||||
| model.model_rebuild() | ||||
| except (PydanticUndefinedAnnotation, PydanticSchemaGenerationError): | ||||
| # If rebuilding fails due to undefined annotations or schema generation errors, | ||||
| # continue anyway as the model might still be usable | ||||
| pass | ||||
|
|
||||
| fields = [] | ||||
| for name, info in _get_schema_items(model, mode): | ||||
|
|
@@ -219,7 +246,7 @@ def create_json_spark_schema( | |||
| try: | ||||
| if _is_base_model(field_type): | ||||
| spark_type = create_json_spark_schema( | ||||
| field_type, safe_casting, by_alias, mode, exclude_fields | ||||
| field_type, safe_casting, by_alias, mode, exclude_fields, _visited_models | ||||
| ) | ||||
| elif override is not None: | ||||
| if isinstance(override, str): | ||||
|
|
@@ -232,20 +259,51 @@ def create_json_spark_schema( | |||
| msg = '`spark_type` override should be a `str` type name (e.g. long)' | ||||
| if utils.have_pyspark: | ||||
| msg += ' or `pyspark.sql.types.DataType` (e.g. LongType)' | ||||
| msg += f', but got {override}' | ||||
| msg += f", but got {override}" | ||||
| raise TypeError(msg) | ||||
| elif isinstance(field_type, str): | ||||
| spark_type = field_type | ||||
| # field_type is a string (likely an unresolved forward reference) | ||||
| # Try to get it from the model's namespace | ||||
| if hasattr(model, '__module__'): | ||||
| import sys | ||||
|
||||
| import sys |
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The circular reference detection logic creates a copy of the visited models set for each recursive call, which could be inefficient for deeply nested structures. Consider using a context manager or tracking depth instead of copying the entire set each time.