Skip to content

Commit

Permalink
Add serialize_by_alias and namedtuple_as_dict dialect options
Browse files Browse the repository at this point in the history
  • Loading branch information
Fatal1ty committed Nov 20, 2023
1 parent 54451e9 commit 097c4c7
Show file tree
Hide file tree
Showing 8 changed files with 42 additions and 17 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -387,10 +387,10 @@ to override some settings if necessary.
> As for codecs, you are
> offered to choose between convenience and efficiency. When you need to decode
> or encode structured data more than once, it's highly recommended to create
> a decoder or encoder specifically for that structure. For one-time use with
> default settings it may be convenient to use global functions that create
> a disposable decoder or encoder under the hood. Be aware not to use these
> convenient global functions in performance-critical code!
> and reuse a decoder or encoder specifically for that structure. For one-time
> use with default settings it may be convenient to use global functions that
> create a disposable decoder or encoder under the hood. Be aware not to use
> these convenient global functions multiple times for the same structure.
### Basic form

Expand Down
2 changes: 1 addition & 1 deletion mashumaro/codecs/_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def add_encode_method(
builder=self,
field_ctx=FieldContext(name="", metadata={}),
could_be_none=could_be_none,
no_copy_collections=self._get_dialect_or_config_option(
no_copy_collections=self.get_dialect_or_config_option(
"no_copy_collections", ()
),
)
Expand Down
4 changes: 3 additions & 1 deletion mashumaro/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ class BaseConfig:
serialize_by_alias: Union[
bool, Literal[Sentinel.MISSING]
] = Sentinel.MISSING
namedtuple_as_dict: bool = False
namedtuple_as_dict: Union[
bool, Literal[Sentinel.MISSING]
] = Sentinel.MISSING
allow_postponed_evaluation: bool = True
dialect: Optional[Type[Dialect]] = None
omit_none: Union[bool, Literal[Sentinel.MISSING]] = Sentinel.MISSING
Expand Down
16 changes: 8 additions & 8 deletions mashumaro/core/meta/code/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -719,15 +719,15 @@ def get_pack_method_default_flag_values(
TO_DICT_ADD_OMIT_NONE_FLAG, cls
)
if omit_none_feature:
omit_none = self._get_dialect_or_config_option("omit_none", False)
omit_none = self.get_dialect_or_config_option("omit_none", False)
kw_param_names.append("omit_none")
kw_param_values.append("True" if omit_none else "False")

by_alias_feature = self.is_code_generation_option_enabled(
TO_DICT_ADD_BY_ALIAS_FLAG, cls
)
if by_alias_feature:
serialize_by_alias = self._get_dialect_or_config_option(
serialize_by_alias = self.get_dialect_or_config_option(
"serialize_by_alias", False, cls
)
kw_param_names.append("by_alias")
Expand Down Expand Up @@ -886,11 +886,11 @@ def _add_pack_method_lines(self, method_name: str) -> None:
omit_none_feature = self.is_code_generation_option_enabled(
TO_DICT_ADD_OMIT_NONE_FLAG
)
serialize_by_alias = self._get_dialect_or_config_option(
serialize_by_alias = self.get_dialect_or_config_option(
"serialize_by_alias", False
)
omit_none = self._get_dialect_or_config_option("omit_none", False)
omit_default = self._get_dialect_or_config_option(
omit_none = self.get_dialect_or_config_option("omit_none", False)
omit_default = self.get_dialect_or_config_option(
"omit_default", False
)
force_value = omit_default
Expand Down Expand Up @@ -1080,7 +1080,7 @@ def __pack_method_set_value(
with self.indent("else:"):
self.add_line(f"kwargs['{fname}'] = {packed_value}")
else:
serialize_by_alias = self._get_dialect_or_config_option(
serialize_by_alias = self.get_dialect_or_config_option(
"serialize_by_alias", False
)
if serialize_by_alias and alias is not None:
Expand Down Expand Up @@ -1213,7 +1213,7 @@ def _get_field_packer(
metadata=metadata,
),
could_be_none=False,
no_copy_collections=self._get_dialect_or_config_option(
no_copy_collections=self.get_dialect_or_config_option(
"no_copy_collections", ()
),
)
Expand Down Expand Up @@ -1246,7 +1246,7 @@ def __iter_serialization_strategies(
if self.default_dialect is not None:
yield self.default_dialect.serialization_strategy.get(ftype)

def _get_dialect_or_config_option(
def get_dialect_or_config_option(
self,
option: str,
default: typing.Any,
Expand Down
4 changes: 3 additions & 1 deletion mashumaro/core/meta/types/pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,9 @@ def pack_named_tuple(spec: ValueSpec) -> Expression:
}
fields = getattr(spec.type, "_fields", ())
packers = []
as_dict = spec.builder.get_config().namedtuple_as_dict
as_dict = spec.builder.get_dialect_or_config_option(
"namedtuple_as_dict", False
)
serialize_option = get_overridden_serialization_method(spec)
if serialize_option is not None:
if serialize_option == "as_dict":
Expand Down
4 changes: 3 additions & 1 deletion mashumaro/core/meta/types/unpack.py
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,9 @@ def unpack_named_tuple(spec: ValueSpec) -> Expression:
fields = getattr(spec.type, "_fields", ())
defaults = getattr(spec.type, "_field_defaults", {})
unpackers = []
as_dict = spec.builder.get_config().namedtuple_as_dict
as_dict = spec.builder.get_dialect_or_config_option(
"namedtuple_as_dict", False
)
deserialize_option = get_overridden_deserialization_method(spec)
if deserialize_option is not None:
if deserialize_option == "as_dict":
Expand Down
7 changes: 7 additions & 0 deletions mashumaro/dialect.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@

class Dialect:
serialization_strategy: Dict[Any, SerializationStrategyValueType] = {}
# TODO: надо в документацию добавить про новые опции
serialize_by_alias: Union[
bool, Literal[Sentinel.MISSING]
] = Sentinel.MISSING
namedtuple_as_dict: Union[
bool, Literal[Sentinel.MISSING]
] = Sentinel.MISSING
omit_none: Union[bool, Literal[Sentinel.MISSING]] = Sentinel.MISSING
omit_default: Union[bool, Literal[Sentinel.MISSING]] = Sentinel.MISSING
no_copy_collections: Union[
Expand Down
14 changes: 13 additions & 1 deletion mashumaro/jsonschema/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,16 @@ def get_owner_config(self) -> Type[BaseConfig]:
else:
return BaseConfig

def get_owner_dialect_or_config_option(
self, option: str, default: Any
) -> Any:
if self.__owner_builder:
return self.__owner_builder.get_dialect_or_config_option(
option, default
)
else:
return default

def get_self_config(self) -> Type[BaseConfig]:
if self.__self_builder:
return self.__self_builder.get_config()
Expand Down Expand Up @@ -606,7 +616,9 @@ def on_named_tuple(instance: Instance, ctx: Context) -> JSONSchema:
}
fields = getattr(instance.type, "_fields", ())
defaults = getattr(instance.type, "_field_defaults", {})
as_dict = instance.get_owner_config().namedtuple_as_dict
as_dict = instance.get_owner_dialect_or_config_option(
"namedtuple_as_dict", False
)
serialize_option = instance.get_overridden_serialization_method()
if serialize_option == "as_dict":
as_dict = True
Expand Down

0 comments on commit 097c4c7

Please sign in to comment.