Skip to content
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

Add support for instance method reassignment when extra='allow' #7683

Merged
merged 7 commits into from Oct 2, 2023
10 changes: 8 additions & 2 deletions pydantic/main.py
Expand Up @@ -798,8 +798,14 @@ def __setattr__(self, name: str, value: Any) -> None:
# TODO - matching error
raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"')
elif self.model_config.get('extra') == 'allow' and name not in self.model_fields:
# SAFETY: __pydantic_extra__ is not None when extra = 'allow'
self.__pydantic_extra__[name] = value # type: ignore
if self.model_extra and name in self.model_extra:
self.__pydantic_extra__[name] = value # type: ignore
else:
attr_exists_on_instance: Any = getattr(self, name, None)
sydney-runkle marked this conversation as resolved.
Show resolved Hide resolved
if attr_exists_on_instance:
_object_setattr(self, name, value)
else:
self.__pydantic_extra__[name] = value # type: ignore
else:
self.__dict__[name] = value
self.__pydantic_fields_set__.add(name)
Expand Down
37 changes: 37 additions & 0 deletions tests/test_main.py
Expand Up @@ -342,6 +342,43 @@ class Model(BaseModel):
assert model.c == 1


def test_reassign_static_method_with_extra_allow():
class Model(BaseModel):
model_config = ConfigDict(extra='allow')

@staticmethod
def not_extra_func(name: str) -> str:
return f'hello {name}'

def not_extra_func_replacement(name: str) -> str:
return f'hi {name}'

m = Model()
assert m.not_extra_func(name='james') == 'hello james'

m.not_extra_func = not_extra_func_replacement
assert m.not_extra_func(name='james') == 'hi james'
assert 'not_extra_func' in m.__dict__


def test_reassign_class_method_with_extra_allow():
class Model(BaseModel):
model_config = ConfigDict(extra='allow')
name: ClassVar[str] = 'julia'

@classmethod
def not_extra_func(cls) -> str:
return f'hello {cls.name}'

def not_extra_func_replacement(cls_sub: Type[Model] = Model) -> str:
return f'hi {cls_sub.name}'

assert Model.not_extra_func() == 'hello julia'

Model.not_extra_func = not_extra_func_replacement
assert Model.not_extra_func() == 'hi julia'


def test_extra_ignored():
class Model(BaseModel):
model_config = ConfigDict(extra='ignore')
Expand Down