Python dataclasses.InitVar() Examples
The following are 13
code examples of dataclasses.InitVar().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
dataclasses
, or try the search function
.
Example #1
Source File: typed_json_dataclass.py From typed-json-dataclass with MIT License | 6 votes |
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
Example #2
Source File: test_dataclasses.py From pydantic with MIT License | 6 votes |
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'"
Example #3
Source File: test_dataclasses.py From pydantic with MIT License | 6 votes |
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')
Example #4
Source File: _unpack.py From undictify with MIT License | 5 votes |
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
Example #5
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_init_var_with_init_var(): assert is_init_var(InitVar[int])
Example #6
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_instance_with_init_var_and_matching_value_type(): assert is_instance(1, InitVar[int])
Example #7
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_instance_with_init_var_and_not_matching_value_type(): assert not is_instance(1, InitVar[str])
Example #8
Source File: test_init_var.py From dacite with MIT License | 5 votes |
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
Example #9
Source File: types.py From dacite with MIT License | 5 votes |
def is_init_var(type_: Type) -> bool: return isinstance(type_, InitVar) or type_ is InitVar
Example #10
Source File: test_data_types.py From mashumaro with Apache License 2.0 | 5 votes |
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()
Example #11
Source File: helpers.py From mashumaro with Apache License 2.0 | 5 votes |
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
Example #12
Source File: test_dataclasses.py From pydantic with MIT License | 5 votes |
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
Example #13
Source File: test_dataclasses.py From pydantic with MIT License | 5 votes |
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')