本文整理汇总了Python中dataclasses.InitVar方法的典型用法代码示例。如果您正苦于以下问题:Python dataclasses.InitVar方法的具体用法?Python dataclasses.InitVar怎么用?Python dataclasses.InitVar使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dataclasses
的用法示例。
在下文中一共展示了dataclasses.InitVar方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _contains_non_default_init_vars
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def _contains_non_default_init_vars(cls, previous_classes=None):
"""Check whether this dataclass contains non-default init-only vars.
Performs a recursive check through all fields that are declared as
dataclasses to ensure that no nested dataclasses contain init-only
variables. The ``previous_classes`` argument is a set of previously
checked classes to prevent infinite recursion on recursive structures.
:param previous_classes: The set of previously checked classes.
"""
try:
previous_classes.add(cls)
except AttributeError: # NoneType
previous_classes = {cls}
# The identify check (.. is MISSING) is fine, MISSING is a singleton
has_init_vars = any(field.type == InitVar and field.default is MISSING
for field in cls.__dataclass_fields__.values())
children_have_init_vars = any(
child.type._contains_non_default_init_vars(previous_classes)
for child in fields(cls)
if (is_dataclass(child.type)
and child.type not in previous_classes))
return has_init_vars or children_have_init_vars
示例2: test_initvars_post_init
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def test_initvars_post_init():
@pydantic.dataclasses.dataclass
class PathDataPostInit:
path: Path
base_path: dataclasses.InitVar[Optional[Path]] = None
def __post_init__(self, base_path):
if base_path is not None:
self.path = base_path / self.path
path_data = PathDataPostInit('world')
assert 'path' in path_data.__dict__
assert 'base_path' not in path_data.__dict__
assert path_data.path == Path('world')
with pytest.raises(TypeError) as exc_info:
PathDataPostInit('world', base_path='/hello')
assert str(exc_info.value) == "unsupported operand type(s) for /: 'str' and 'str'"
示例3: test_initvars_post_init_post_parse
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def test_initvars_post_init_post_parse():
@pydantic.dataclasses.dataclass
class PathDataPostInitPostParse:
path: Path
base_path: dataclasses.InitVar[Optional[Path]] = None
def __post_init_post_parse__(self, base_path):
if base_path is not None:
self.path = base_path / self.path
path_data = PathDataPostInitPostParse('world')
assert 'path' in path_data.__dict__
assert 'base_path' not in path_data.__dict__
assert path_data.path == Path('world')
assert PathDataPostInitPostParse('world', base_path='/hello').path == Path('/hello/world')
示例4: _is_initvar_type
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def _is_initvar_type(the_type: Callable[..., TypeT]) -> bool:
"""Return True if the type is an InitVar
In Python 3.7, InitVar is essentially a singleton.
InitVar[str] == InitVar[int]
In Python 3.8, InitVar can be a singleton, or an instance.
InitVar[str] != InitVar[int], but InitVar == InitVar
Therefore, the code below checks for both cases to support 3.7 and 3.8
"""
if VER_3_7_AND_UP:
return the_type == InitVar or isinstance(the_type, InitVar) # type: ignore
return False
示例5: test_is_init_var_with_init_var
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def test_is_init_var_with_init_var():
assert is_init_var(InitVar[int])
示例6: test_is_instance_with_init_var_and_matching_value_type
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def test_is_instance_with_init_var_and_matching_value_type():
assert is_instance(1, InitVar[int])
示例7: test_is_instance_with_init_var_and_not_matching_value_type
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def test_is_instance_with_init_var_and_not_matching_value_type():
assert not is_instance(1, InitVar[str])
示例8: test_from_dict_with_init_var
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def test_from_dict_with_init_var():
@dataclass
class X:
a: InitVar[int]
b: Optional[int] = None
def __post_init__(self, a: int) -> None:
self.b = 2 * a
result = from_dict(X, {"a": 2})
assert result.b == 4
示例9: is_init_var
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def is_init_var(type_: Type) -> bool:
return isinstance(type_, InitVar) or type_ is InitVar
示例10: test_init_vars
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def test_init_vars():
@dataclass
class DataClass(DataClassDictMixin):
x: InitVar[int] = None
y: int = None
def __post_init__(self, x: int):
if self.y is None and x is not None:
self.y = x
assert DataClass().to_dict() == {'y': None}
assert DataClass(x=1).to_dict() == {'y': 1}
assert DataClass.from_dict({}) == DataClass()
assert DataClass.from_dict({'x': 1}) == DataClass()
示例11: is_init_var
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def is_init_var(t):
if PY_36 or PY_37:
return get_type_origin(t) is dataclasses.InitVar
elif PY_38:
return isinstance(t, dataclasses.InitVar)
else:
raise NotImplementedError
示例12: test_initvar
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def test_initvar():
InitVar = dataclasses.InitVar
@pydantic.dataclasses.dataclass
class TestInitVar:
x: int
y: InitVar
tiv = TestInitVar(1, 2)
assert tiv.x == 1
with pytest.raises(AttributeError):
tiv.y
示例13: test_derived_field_from_initvar
# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import InitVar [as 别名]
def test_derived_field_from_initvar():
InitVar = dataclasses.InitVar
@pydantic.dataclasses.dataclass
class DerivedWithInitVar:
plusone: int = dataclasses.field(init=False)
number: InitVar[int]
def __post_init__(self, number):
self.plusone = number + 1
derived = DerivedWithInitVar(1)
assert derived.plusone == 2
with pytest.raises(TypeError):
DerivedWithInitVar('Not A Number')