Skip to content

Commit

Permalink
use existing method to bind type name for compilation
Browse files Browse the repository at this point in the history
  • Loading branch information
mishamsk committed Dec 3, 2023
1 parent d7f5a88 commit ba0483e
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 10 deletions.
13 changes: 6 additions & 7 deletions mashumaro/core/meta/code/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,15 @@
is_hashable,
is_init_var,
is_literal,
is_local_type,
is_named_tuple,
is_optional,
is_type_var_any,
resolve_type_params,
substitute_type_params,
type_name,
)
from mashumaro.core.meta.types.common import FieldContext, NoneType, ValueSpec
from mashumaro.core.meta.types.common import FieldContext, NoneType, ValueSpec, clean_id
from mashumaro.core.meta.types.pack import PackerRegistry
from mashumaro.core.meta.types.unpack import (
SubtypeUnpackerBuilder,
Expand Down Expand Up @@ -80,8 +81,6 @@
__POST_SERIALIZE__ = "__post_serialize__"
__POST_DESERIALIZE__ = "__post_deserialize__"

_LOCALS_TYPE_VAR = "__locals_type_var__"


class InternalMethodName(str):
_PREFIX = "__mashumaro_"
Expand Down Expand Up @@ -306,8 +305,7 @@ def compile(self) -> None:
print(f"{type_name(self.cls)}:")
print(code)

localns = {**self.__dict__, _LOCALS_TYPE_VAR: self.cls}
exec(code, self.globals, localns)
exec(code, self.globals, self.__dict__)

def evaluate_forward_ref(
self,
Expand Down Expand Up @@ -560,8 +558,9 @@ def _unpack_method_set_value(
resolved_type_params=self.get_field_resolved_type_params(fname),
)

if "<locals>" in field_type:
field_type = _LOCALS_TYPE_VAR
if is_local_type(ftype):
field_type = clean_id(field_type)
self.ensure_object_imported(ftype, field_type)

could_be_none = (
ftype in (typing.Any, type(None), None)
Expand Down
2 changes: 2 additions & 0 deletions mashumaro/core/meta/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,8 @@ def is_literal(typ: Type) -> bool:
return type(typ) is typing._LiteralGenericAlias # type: ignore
return False

def is_local_type(typ: Type) -> bool:
return "<locals>" in getattr(typ, "__qualname__", "")

def not_none_type_arg(
type_args: Tuple[Type, ...],
Expand Down
9 changes: 6 additions & 3 deletions mashumaro/core/meta/types/common.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import collections.abc
import re
import uuid
from abc import ABC, abstractmethod
from dataclasses import dataclass, field, replace
Expand Down Expand Up @@ -302,8 +303,10 @@ def expr_or_maybe_none(spec: ValueSpec, new_expr: Expression) -> Expression:
def random_hex() -> str:
return str(uuid.uuid4().hex)

_PY_VALID_ID_RE = re.compile(r"\W|^(?=\d)")

def clean_id(value: str) -> str:
for c in ".<>":
value = value.replace(c, "_")
return value
if not value:
return "_"

return _PY_VALID_ID_RE.sub("_", value)

0 comments on commit ba0483e

Please sign in to comment.