How to use the dataclasses.InitVar function in dataclasses

To help you get started, we’ve selected a few dataclasses examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github samuelcolvin / pydantic / tests / test_dataclasses.py View on Github external
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'"
github samuelcolvin / pydantic / tests / test_dataclasses.py View on Github external
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')
github axbaretto / beam / sdks / python / apache_beam / transforms / external_test_py37.py View on Github external
def get_payload_from_typing_hints(self, values):

    @dataclasses.dataclass
    class DataclassTransform(beam.ExternalTransform):
      URN = 'beam:external:fakeurn:v1'

      integer_example: int
      boolean: bool
      string_example: str
      list_of_strings: typing.List[str]
      optional_kv: typing.Optional[typing.Tuple[str, float]] = None
      optional_integer: typing.Optional[int] = None
      expansion_service: dataclasses.InitVar[typing.Optional[str]] = None

    return get_payload(DataclassTransform(**values))
github Fatal1ty / mashumaro / tests / test_data_types.py View on Github external
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()
github Dobiasd / undictify / undictify / _unpack.py View on Github external
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
github ppoelzl / PathOfBuildingAPI / pobapi / config.py View on Github external
enemy_covered_in_ash: bool = False
    enemy_rare_or_unique: bool = False
    enemy_boss: Union[bool, str] = False
    enemy_physical_damage_reduction: int = None
    enemy_fire_resist: int = None
    enemy_cold_resist: int = None
    enemy_lightning_resist: int = None
    enemy_chaos_resist: int = None
    enemy_hit_by_fire_damage: bool = False
    enemy_hit_by_cold_damage: bool = False
    enemy_hit_by_lightning_damage: bool = False
    elemental_equilibrium_ignore_hit_damage: bool = False
    # The fields in the post init method are the only values in Path of Building's
    # configuration tab that are calculated, but can also be overridden so we
    # potentially have to initialise them at a later point in time.
    character_level: InitVar[int] = None

    # TODO: Raise Spectre level calc on 3.0.0+
    def __post_init__(self, character_level: int):
        if character_level is None:
            character_level = 84
        if self.enemy_level is None:
            self.enemy_level = min(character_level, 84)
        if self.enemy_physical_hit_damage is None:
            self.enemy_physical_hit_damage = (
                MONSTER_DAMAGE_TABLE[self.enemy_level - 1] * 1.5
            )
        if self.detonate_dead_corpse_life is None:
            self.detonate_dead_corpse_life = MONSTER_LIFE_TABLE[self.enemy_level - 1]
github Fatal1ty / mashumaro / mashumaro / meta / helpers.py View on Github external
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
github thread / routemaster / routemaster / feeds.py View on Github external
def _get_feed_session():
    # We cache sessions per thread so that we can use `requests.Session`'s
    # underlying `urllib3` connection pooling.
    if not hasattr(_feed_sessions, 'session'):
        _feed_sessions.session = requests.Session()
    return _feed_sessions.session


@dataclass
class Feed:
    """A feed fetcher, able to retreive a feed and read keys out of it."""
    url: str
    state_machine: str
    data: InitVar[Optional[Dict[str, Any]]] = None

    def prefetch(
        self,
        label: str,
        log_response: Callable[[requests.Response], None] = lambda x: None,
    ) -> None:
        """Trigger the fetching of a feed's data."""
        if self.data is not None:
            return

        url = template_url(self.url, self.state_machine, label)

        session = _get_feed_session()
        response = session.get(url)
        log_response(response)
        response.raise_for_status()
github dropbox / merou / grouper / fe / templates.py View on Github external
template: InitVar[str] = "permission.html"


@dataclass(repr=False, eq=False)
class PermissionsTemplate(BaseTemplate):
    permissions: List[Permission]
    offset: int
    limit: int
    total: int
    can_create: bool
    audited_permissions: bool
    sort_key: str
    sort_dir: str

    template: InitVar[str] = "permissions.html"


@dataclass(repr=False, eq=False)
class ServiceAccountCreateTemplate(BaseTemplate):
    owner: str
    form: ServiceAccountCreateForm

    template: InitVar[str] = "service-account-create.html"


@dataclass(repr=False, eq=False)
class ServiceAccountPermissionGrantTemplate(BaseTemplate):
    service: str
    owner: str
    form: ServiceAccountPermissionGrantForm
github Fatal1ty / mashumaro / mashumaro / meta / helpers.py View on Github external
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