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 exclude_private parameter #1139

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions pydantic/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def __init__(__pydantic_self__, **data: Any) -> None:

@no_type_check
def __setattr__(self, name, value):
if self.__config__.extra is not Extra.allow and name not in self.__fields__:
if self.__config__.extra is Extra.forbid and name not in self.__fields__:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if self.__config__.extra is Extra.forbid and name not in self.__fields__:
if name.startswith('_'):
self.__dict__[name] = value
return
if self.__config__.extra is not Extra.allow and name not in self.__fields__:

raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"')
elif not self.__config__.allow_mutation:
raise TypeError(f'"{self.__class__.__name__}" is immutable and does not support item assignment')
Expand Down Expand Up @@ -307,6 +307,7 @@ def dict(
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
exclude_private: bool = True,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove this, I think it's safe to always exclude anything in __dict__ where the key startswith with _.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But this would break concept when we have only parsed values in __dict__ and will force additional checks, etc.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from pydantic import BaseModel, Extra

class Record(BaseModel):
    class Config:
        extra = Extra.allow

print(Record(_a='b'))  # _a='b'

) -> 'DictStrAny':
"""
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
Expand All @@ -332,6 +333,7 @@ def dict(
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
exclude_private=exclude_private
)
}

Expand All @@ -351,6 +353,7 @@ def json(
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
exclude_private: bool = True,
encoder: Optional[Callable[[Any], Any]] = None,
**dumps_kwargs: Any,
) -> str:
Expand All @@ -373,6 +376,7 @@ def json(
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
exclude_private=exclude_private,
)
if self.__custom_root_type__:
data = data[ROOT_KEY]
Expand Down Expand Up @@ -641,6 +645,7 @@ def _iter(
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
exclude_private: bool = True,
) -> 'TupleGenerator':

value_exclude = ValueItems(self, exclude) if exclude else None
Expand All @@ -654,6 +659,8 @@ def _iter(
allowed_keys.discard(k)

for k, v in self.__dict__.items():
if exclude_private and k.startswith('_'):
continue
if allowed_keys is None or k in allowed_keys:
value = self._get_value(
v,
Expand All @@ -663,7 +670,7 @@ def _iter(
exclude=value_exclude and value_exclude.for_element(k),
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
exclude_none=exclude_none
)
if not (exclude_none and value is None):
yield k, value
Expand Down