Python attr.has() Examples

The following are 30 code examples of attr.has(). 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 attr , or try the search function .
Example #1
Source File: test_validators.py    From attrs with MIT License 6 votes vote down vote up
def test_repr(self):
        """
        Returned validator has a useful `__repr__`.
        """
        key_validator = instance_of(str)
        key_repr = "<instance_of validator for type <{type} 'str'>>".format(
            type=TYPE
        )
        value_validator = instance_of(int)
        value_repr = "<instance_of validator for type <{type} 'int'>>".format(
            type=TYPE
        )
        v = deep_mapping(key_validator, value_validator)
        expected_repr = (
            "<deep_mapping validator for objects mapping "
            "{key_repr} to {value_repr}>"
        ).format(key_repr=key_repr, value_repr=value_repr)
        assert expected_repr == repr(v) 
Example #2
Source File: test_validators.py    From attrs with MIT License 6 votes vote down vote up
def test_repr(self, validator):
        """
        Returned validator has a useful `__repr__`.
        """
        v = optional(validator)

        if isinstance(validator, list):
            repr_s = (
                "<optional validator for _AndValidator(_validators=[{func}, "
                "<instance_of validator for type <{type} 'int'>>]) or None>"
            ).format(func=repr(always_pass), type=TYPE)
        else:
            repr_s = (
                "<optional validator for <instance_of validator for type "
                "<{type} 'int'>> or None>"
            ).format(type=TYPE)

        assert repr_s == repr(v) 
Example #3
Source File: py_typecheck.py    From federated with Apache License 2.0 6 votes vote down vote up
def is_named_tuple(value):
  """Determines whether `value` can be considered a `collections.namedtuple`.

  As `collections.namedtuple` creates a new class with no common a base for each
  named tuple, there is no simple way to check the type with `isintance(T)`.
  Instead, this method looks to see if `value` has an `_fields` attribute (which
  all namedtuple subclasses support).

  Args:
    value: an instance of a Python class or a Python type object.

  Returns:
    True iff `value` can be considered an instance or type of
    `collections.namedtuple`.
  """
  if isinstance(value, type):
    return issubclass(value, tuple) and hasattr(value, '_fields')
  else:
    return is_named_tuple(type(value)) 
Example #4
Source File: test_funcs.py    From attrs with MIT License 6 votes vote down vote up
def test_recurse_property(self, cls, tuple_class):
        """
        Property tests for recursive astuple.
        """
        obj = cls()
        obj_tuple = astuple(obj, tuple_factory=tuple_class)

        def assert_proper_tuple_class(obj, obj_tuple):
            assert isinstance(obj_tuple, tuple_class)
            for index, field in enumerate(fields(obj.__class__)):
                field_val = getattr(obj, field.name)
                if has(field_val.__class__):
                    # This field holds a class, recurse the assertions.
                    assert_proper_tuple_class(field_val, obj_tuple[index])

        assert_proper_tuple_class(obj, obj_tuple) 
Example #5
Source File: attrs.py    From nata with MIT License 5 votes vote down vote up
def is_identifier(instance, attribute, value):
    if not value.isidentifier():
        raise ValueError(
            f"attribute {attribute.name} has an invalid string '{value}'"
        ) 
Example #6
Source File: test_validators.py    From attrs with MIT License 5 votes vote down vote up
def test_hashability():
    """
    Validator classes are hashable.
    """
    for obj_name in dir(validator_module):
        obj = getattr(validator_module, obj_name)
        if not has(obj):
            continue
        hash_func = getattr(obj, "__hash__", None)
        assert hash_func is not None
        assert hash_func is not object.__hash__ 
Example #7
Source File: test_validators.py    From attrs with MIT License 5 votes vote down vote up
def test_exception_repr(self):
        """
        Verify that NotCallableError exception has a useful `__str__`.
        """
        from attr.exceptions import NotCallableError

        instance = NotCallableError(msg="Some Message", value=42)
        assert "Some Message" == str(instance) 
Example #8
Source File: test_validators.py    From attrs with MIT License 5 votes vote down vote up
def test_repr(self):
        """
        Returned validator has a useful `__repr__`.
        """
        v = is_callable()
        assert "<is_callable validator>" == repr(v) 
Example #9
Source File: test_validators.py    From attrs with MIT License 5 votes vote down vote up
def test_repr_member_only(self):
        """
        Returned validator has a useful `__repr__`
        when only member validator is set.
        """
        member_validator = instance_of(int)
        member_repr = "<instance_of validator for type <{type} 'int'>>".format(
            type=TYPE
        )
        v = deep_iterable(member_validator)
        expected_repr = (
            "<deep_iterable validator for iterables of {member_repr}>"
        ).format(member_repr=member_repr)
        assert ((expected_repr)) == repr(v) 
Example #10
Source File: test_validators.py    From attrs with MIT License 5 votes vote down vote up
def test_repr(self):
        """
        Returned validator has a useful `__repr__`.
        """
        v = in_([3, 4, 5])
        assert (("<in_ validator with options [3, 4, 5]>")) == repr(v) 
Example #11
Source File: test_validators.py    From attrs with MIT License 5 votes vote down vote up
def test_repr(self):
        """
        Returned validator has a useful `__repr__`.
        """
        v = provides(IFoo)
        assert (
            "<provides validator for interface {interface!r}>".format(
                interface=IFoo
            )
        ) == repr(v) 
Example #12
Source File: test_validators.py    From attrs with MIT License 5 votes vote down vote up
def test_repr(self):
        """
        Returned validator has a useful `__repr__`.
        """
        v = instance_of(int)
        assert (
            "<instance_of validator for type <{type} 'int'>>".format(type=TYPE)
        ) == repr(v) 
Example #13
Source File: test_funcs.py    From attrs with MIT License 5 votes vote down vote up
def test_positive_empty(self):
        """
        Returns `True` on decorated classes even if there are no attributes.
        """

        @attr.s
        class D(object):
            pass

        assert has(D) 
Example #14
Source File: test_funcs.py    From attrs with MIT License 5 votes vote down vote up
def test_positive(self, C):
        """
        Returns `True` on decorated classes.
        """
        assert has(C) 
Example #15
Source File: test_funcs.py    From attrs with MIT License 5 votes vote down vote up
def test_recurse_retain(self, cls, tuple_class):
        """
        Property tests for asserting collection types are retained.
        """
        obj = cls()
        obj_tuple = astuple(
            obj, tuple_factory=tuple_class, retain_collection_types=True
        )

        def assert_proper_col_class(obj, obj_tuple):
            # Iterate over all attributes, and if they are lists or mappings
            # in the original, assert they are the same class in the dumped.
            for index, field in enumerate(fields(obj.__class__)):
                field_val = getattr(obj, field.name)
                if has(field_val.__class__):
                    # This field holds a class, recurse the assertions.
                    assert_proper_col_class(field_val, obj_tuple[index])
                elif isinstance(field_val, (list, tuple)):
                    # This field holds a sequence of something.
                    expected_type = type(obj_tuple[index])
                    assert type(field_val) is expected_type
                    for obj_e, obj_tuple_e in zip(field_val, obj_tuple[index]):
                        if has(obj_e.__class__):
                            assert_proper_col_class(obj_e, obj_tuple_e)
                elif isinstance(field_val, dict):
                    orig = field_val
                    tupled = obj_tuple[index]
                    assert type(orig) is type(tupled)
                    for obj_e, obj_tuple_e in zip(
                        orig.items(), tupled.items()
                    ):
                        if has(obj_e[0].__class__):  # Dict key
                            assert_proper_col_class(obj_e[0], obj_tuple_e[0])
                        if has(obj_e[1].__class__):  # Dict value
                            assert_proper_col_class(obj_e[1], obj_tuple_e[1])

        assert_proper_col_class(obj, obj_tuple) 
Example #16
Source File: test_funcs.py    From attrs with MIT License 5 votes vote down vote up
def test_recurse_property(self, cls, dict_class):
        """
        Property tests for recursive asdict.
        """
        obj = cls()
        obj_dict = asdict(obj, dict_factory=dict_class)

        def assert_proper_dict_class(obj, obj_dict):
            assert isinstance(obj_dict, dict_class)

            for field in fields(obj.__class__):
                field_val = getattr(obj, field.name)
                if has(field_val.__class__):
                    # This field holds a class, recurse the assertions.
                    assert_proper_dict_class(field_val, obj_dict[field.name])
                elif isinstance(field_val, Sequence):
                    dict_val = obj_dict[field.name]
                    for item, item_dict in zip(field_val, dict_val):
                        if has(item.__class__):
                            assert_proper_dict_class(item, item_dict)
                elif isinstance(field_val, Mapping):
                    # This field holds a dictionary.
                    assert isinstance(obj_dict[field.name], dict_class)

                    for key, val in field_val.items():
                        if has(val.__class__):
                            assert_proper_dict_class(
                                val, obj_dict[field.name][key]
                            )

        assert_proper_dict_class(obj, obj_dict) 
Example #17
Source File: logging.py    From k8s-snapshots with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __structlog__(self):
        if attr.has(self.__class__):
            return attr.asdict(self)

        if hasattr(self, 'to_dict') and callable(self.to_dict):
            return self.to_dict()

        return self 
Example #18
Source File: _utils.py    From omegaconf with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_attr_class(obj: Any) -> bool:
    from omegaconf.base import Node

    if attr is None or isinstance(obj, Node):
        return False
    return attr.has(obj) 
Example #19
Source File: serializable_attrs.py    From mautrix-python with Mozilla Public License 2.0 5 votes vote down vote up
def _serialize(val: Any) -> JSON:
    if isinstance(val, Serializable):
        return val.serialize()
    elif isinstance(val, (tuple, list, set)):
        return [_serialize(subval) for subval in val]
    elif isinstance(val, dict):
        return {_serialize(subkey): _serialize(subval) for subkey, subval in val.items()}
    elif attr.has(val.__class__):
        return _attrs_to_dict(val)
    return val 
Example #20
Source File: test_settings.py    From RLs with Apache License 2.0 5 votes vote down vote up
def check_if_different(testobj1: object, testobj2: object) -> None:
    assert testobj1 is not testobj2
    if attr.has(testobj1.__class__) and attr.has(testobj2.__class__):
        for key, val in attr.asdict(testobj1, recurse=False).items():
            if isinstance(val, dict) or isinstance(val, list) or attr.has(val):
                # Note: this check doesn't check the contents of mutables.
                check_if_different(val, attr.asdict(testobj2, recurse=False)[key]) 
Example #21
Source File: settings.py    From RLs with Apache License 2.0 5 votes vote down vote up
def structure(d: Mapping, t: type) -> Any:
        """
        Helper method to structure a TrainerSettings class. Meant to be registered with
        cattr.register_structure_hook() and called with cattr.structure().
        """
        if not isinstance(d, Mapping):
            raise TrainerConfigError(f"Unsupported config {d} for {t.__name__}.")
        d_copy: Dict[str, Any] = {}
        d_copy.update(d)

        for key, val in d_copy.items():
            if attr.has(type(val)):
                # Don't convert already-converted attrs classes.
                continue
            if key == "hyperparameters":
                if "trainer_type" not in d_copy:
                    raise TrainerConfigError(
                        "Hyperparameters were specified but no trainer_type was given."
                    )
                else:
                    d_copy[key] = strict_to_cls(
                        d_copy[key], TrainerType(d_copy["trainer_type"]).to_settings()
                    )
            elif key == "max_steps":
                d_copy[key] = int(float(val))
                # In some legacy configs, max steps was specified as a float
            else:
                d_copy[key] = check_and_structure(key, val, t)
        return t(**d_copy) 
Example #22
Source File: py_typecheck.py    From federated with Apache License 2.0 5 votes vote down vote up
def is_attrs(value):
  """Determines whether `value` is an attrs decorated class or instance of."""
  return attr.has(value) 
Example #23
Source File: baseoperator.py    From airflow with Apache License 2.0 5 votes vote down vote up
def _render_nested_template_fields(
        self, content: Any, context: Dict, jinja_env: jinja2.Environment, seen_oids: Set
    ) -> None:
        if id(content) not in seen_oids:
            seen_oids.add(id(content))
            try:
                nested_template_fields = content.template_fields
            except AttributeError:
                # content has no inner template fields
                return

            self._do_render_template_fields(content, nested_template_fields, context, jinja_env, seen_oids) 
Example #24
Source File: baseoperator.py    From airflow with Apache License 2.0 5 votes vote down vote up
def dag_id(self) -> str:
        """Returns dag id if it has one or an adhoc + owner"""
        if self.has_dag():
            return self.dag.dag_id
        else:
            return 'adhoc_' + self.owner 
Example #25
Source File: baseoperator.py    From airflow with Apache License 2.0 5 votes vote down vote up
def dag(self) -> Any:
        """
        Returns the Operator's DAG if set, otherwise raises an error
        """
        if self.has_dag():
            return self._dag
        else:
            raise AirflowException(
                'Operator {} has not been assigned to a DAG yet'.format(self)) 
Example #26
Source File: baseoperator.py    From airflow with Apache License 2.0 5 votes vote down vote up
def __lt__(self, other):
        """
        Called for [Inlet] > [Operator] or [Operator] < [Inlet], so that if other is
        an attr annotated object it is set as an inlet to this operator
        """
        if not isinstance(other, Iterable):
            other = [other]

        for obj in other:
            if not attr.has(obj):
                raise TypeError(f"{obj} cannot be an inlet")
        self.add_inlets(other)

        return self 
Example #27
Source File: baseoperator.py    From airflow with Apache License 2.0 5 votes vote down vote up
def __gt__(self, other):
        """
        Called for [Operator] > [Outlet], so that if other is an attr annotated object
        it is set as an outlet of this Operator.
        """
        if not isinstance(other, Iterable):
            other = [other]

        for obj in other:
            if not attr.has(obj):
                raise TypeError(f"Left hand side ({obj}) is not an outlet")
        self.add_outlets(other)

        return self 
Example #28
Source File: __init__.py    From airflow with Apache License 2.0 5 votes vote down vote up
def _to_dataset(obj: Any, source: str) -> Optional[Metadata]:
    """
    Create Metadata from attr annotated object
    """
    if not attr.has(obj):
        return None

    type_name = obj.__module__ + '.' + obj.__class__.__name__
    data = unstructure(obj)

    return Metadata(type_name, source, data) 
Example #29
Source File: attrs.py    From nata with MIT License 5 votes vote down vote up
def have_attr(*args):
    if len(args) == 0:
        return False

    for a in args:
        if not attr.has(a.__class__):
            return False

    return True 
Example #30
Source File: serializable_attrs.py    From mautrix-python with Mozilla Public License 2.0 4 votes vote down vote up
def _deserialize(cls: Type[T], value: JSON, default: Optional[T] = None) -> T:
    if value is None:
        return _safe_default(default)

    try:
        deser = deserializer_map[cls]
    except KeyError:
        pass
    else:
        return deser(value)
    supertype = getattr(cls, "__supertype__", None)
    if supertype:
        cls = supertype
        try:
            deser = deserializer_map[supertype]
        except KeyError:
            pass
        else:
            return deser(value)
    if attr.has(cls):
        if _has_custom_deserializer(cls):
            return cls.deserialize(value)
        return _dict_to_attrs(cls, value, default, default_if_empty=True)
    elif cls == Any or cls == JSON:
        return value
    elif getattr(cls, "__origin__", None) is Union:
        if len(cls.__args__) == 2 and isinstance(None, cls.__args__[1]):
            return _deserialize(cls.__args__[0], value, default)
    elif isinstance(cls, type):
        if issubclass(cls, Serializable):
            return cls.deserialize(value)

    type_class = _get_type_class(cls)
    args = getattr(cls, "__args__", None)
    if type_class == list:
        item_cls, = args
        return [_deserialize(item_cls, item) for item in value]
    elif type_class == set:
        item_cls, = args
        return {_deserialize(item_cls, item) for item in value}
    elif type_class == dict:
        key_cls, val_cls = args
        return {_deserialize(key_cls, key): _deserialize(val_cls, item)
                for key, item in value.items()}

    if isinstance(value, list):
        return Lst(value)
    elif isinstance(value, dict):
        return Obj(**value)
    return value