-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Description
Initial Checks
- I have searched GitHub for a duplicate issue and I'm sure this is something new
- I have searched Google & StackOverflow for a solution and couldn't find anything
- I have read and followed the docs and still think this is a bug
- I am confident that the issue is with pydantic (not my code, or another library in the ecosystem like FastAPI or mypy)
Description
Since v1.10.*, it seems that pydantic does not find anymore certain attributes even though they are available in the classes. Moreover, it seems that pydantic.dataclasses.dataclass has some side effects on the provided objects now.
Consider the following MWE where we set up a dummy dataclass
from dataclasses import dataclass as vanilla_dataclass
from dataclasses import field, make_dataclass
from typing import ClassVar
from pydantic.dataclasses import dataclass
class Foo():
bar: str = 'cat'
default_config = make_dataclass(
cls_name=Foo.__name__,
bases=(vanilla_dataclass(Foo),),
fields=[("bar", ClassVar[str], field(default=Foo.bar))]
)Then, we pass this dataclass to pydantic and subsequently ask for the bar attribute:
config = dataclass(default_config)
print("Get Attr", getattr(config, "bar"))
setattr(config, "bar", 'dog')
print("Get Attr", getattr(config, "bar"))In pydantic<=1.9.2, this code runs successfully and will first print cat and then dog.
However since v1.10.* the second last line (setattr(config, "bar", "dog")) will raise:
AttributeError: 'DataclassProxy' object has no attribute 'bar'This is surprising because the attribute is actually there! The third last line will find the attribute and print its value ("cat").
Even more suprisingly, it seems that this issue can be fixed upon calling dataclass twice.
config = dataclass(default_config)
config = dataclass(default_config)
print("Get Attr", getattr(config, "bar"))
setattr(config, "bar", 'dog')
print("Get Attr", getattr(config, "bar"))will run through.
This seems to suggest that dataclass has some side effects on the passed object (default_config).
It would be great to hear your thoughts on this.
Example Code
No response
Python, Pydantic & OS Version
pydantic version: 1.10.2
pydantic compiled: True
install path: /Users/jab/miniconda3/envs/gt4sd/lib/python3.8/site-packages/pydantic
python version: 3.8.13 | packaged by conda-forge | (default, Mar 25 2022, 06:05:47) [Clang 12.0.1 ]
platform: macOS-10.16-x86_64-i386-64bit
optional deps. installed: ['typing-extensions']
Affected Components
- Compatibility between releases
- Data validation/parsing
- Data serialization -
.dict()and.json() - JSON Schema
- Dataclasses
- Model Config
- Field Types - adding or changing a particular data type
- Function validation decorator
- Generic Models
- Other Model behaviour -
construct(), pickling, private attributes, ORM mode - Plugins and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.