Comments (6)
I didn't have a field where it makes sense to provide additional context after the example_code portion, so I have opted to do so here.
In trying to resolve this, I did a little digging and have a few more things to report.
Dismantling the Forward Reference
I thought to try inverting the order of my classes to avoid a forward reference thinking that this would solve the issue. It did not. This code produces the same error as was submitted:
from pydantic import BaseModel
from typing import List, Optional
class StatelessRule(BaseModel):
pass
class StatelessRulesAndCustomActions(BaseModel):
StatelessRules: Optional[List[StatelessRule]] = None
class RulesSource(BaseModel):
StatelessRulesAndCustomActions: Optional["StatelessRulesAndCustomActions"] = None
def test_the_bug():
# Create instances of the classes to trigger type checking
rules_source = RulesSource(StatelessRulesAndCustomActions=StatelessRulesAndCustomActions(StatelessRules=[StatelessRule()]))
Check if Name Collisions Are Allowed
So then I got to thinking that maybe this is just a constraint about Pydantic that I was unaware of and wrote another test using a different, but related, section of my real code. The name collision is definitely allowed when not used with Optional[]
as the below code will execute without any problems in pytest:
from pydantic import BaseModel
from typing import Dict, List
class CustomActionDefinition(BaseModel):
PublishMetricAction: Dict[str, List[Dict[str, str]]]
class CustomAction(BaseModel):
ActionName: str
CustomActionDefinition: CustomActionDefinition
def test_property_name_collision_allowed():
custom_action = CustomAction(
ActionName="foo",
CustomActionDefinition={"PublishMetricAction": {"bar": [{"baz": "buzz"}]}}
)
Check if the problem is really a name collision
At this point, I went back to the original code and renamed StatelessRulesAndCustomActions
to StatelessRulesAndCustomActionsModel
and magically the error went away. The below code runs as expected.
from pydantic import BaseModel
from typing import Dict, List, Optional
class StatelessRule(BaseModel):
pass
class StatelessRulesAndCustomActionsModel(BaseModel):
StatelessRules: Optional[List[StatelessRule]] = None
class RulesSource(BaseModel):
StatelessRulesAndCustomActions: Optional["StatelessRulesAndCustomActionsModel"] = None
def test_the_bug():
# Create instances of the classes to trigger type checking
rules_source = RulesSource(StatelessRulesAndCustomActions=StatelessRulesAndCustomActionsModel(StatelessRules=[StatelessRule()]))
from pydantic.
This seems to be the same issue as: #7327, #8240, #7309 (see #6646 (comment) for an explanation).
See also #9093 (comment), could be the same issue you are facing
from pydantic.
Closing as a duplicate, based on the issues that @Viicos mentioned above. Thanks!
from pydantic.
I read through the source material you provided and I do agree that this is a duplicate; however, I'm having a hard time reconciling why having the Optional[]
type surround the value of the property sharing the same name is what causes this in the current version of Pydantic. If the behavior of the Optional[]
type is responsible for this presentation of the collision error, I would wonder if the root cause of Python's typing hints is actually the root cause.
Do you have any insight into why the name collision was perfectly fine without Optional[]
as I showed in my addenda?
from pydantic.
Not sure, might need to double check, but I think this comes from what I described here: #8243 (comment).
I'll probably need to take a better look at your code example, but could you confirm this matches your use case?
from pydantic.
Since Optional[...]
is shorthand for Union[..., None]
I think that it does.
On this same train, now that Union
types are a thing in Py3.12, the syntax of date: date | None = None
from some of your other examples would probably also run into this issue
from pydantic.
Related Issues (20)
- union_mode='smart' not honored when calling model_dump_json() HOT 2
- Support TypeVar with Identical Bound and Default HOT 1
- `model_json_schema()` turns `float` type to `number` type HOT 6
- __repr__ recursion HOT 4
- Before Model Validators cause type checking issues HOT 1
- Field title with same name as model class leads to unexpected schema behavior HOT 2
- model_dump include/exclude attributes by alias HOT 2
- Memory leak in pydantic model_validate from sqlalchemy model HOT 11
- Input should be a valid datetime, invalid timezone sign HOT 2
- Switching pydantic from 2.6.4 to 2.7.1 removes the dependancies on annotated-types and pydantic-core behind SonartypeNexus Repository Proxy HOT 2
- JSON schemas with circular references HOT 1
- validate_call trying to parse an enum.StrEnum as an int HOT 2
- Clarify documentation of strip_whitespace HOT 2
- Add Python fractions as a natively supported type HOT 1
- Enhance UrlConstraints with allowed_hosts attribute. HOT 1
- Pydantic dataclasses cannot be used as Annotated Validators HOT 1
- JsonValue is contravariant, should be covariant HOT 5
- Cannot use `str` as argument to PlainSerializer HOT 2
- Expose normalization functionality in EmailStr HOT 5
- Unable to Deserialize Model with BaseModel as Dictionary Keys HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pydantic.