Python attr.make_class() Examples
The following are 25
code examples of attr.make_class().
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_make.py From attrs with MIT License | 7 votes |
def test_convert_before_validate(self): """ Validation happens after conversion. """ def validator(inst, attr, val): raise RuntimeError("foo") C = make_class( "C", { "x": attr.ib(validator=validator, converter=lambda v: 1 / 0), "y": attr.ib(), }, ) with pytest.raises(ZeroDivisionError): C(1, 2)
Example #2
Source File: test_make.py From attrs with MIT License | 6 votes |
def test_bases(self): """ Parameter bases default to (object,) and subclasses correctly """ class D(object): pass cls = make_class("C", {}) assert cls.__mro__[-1] == object cls = make_class("C", {}, bases=(D,)) assert D in cls.__mro__ assert isinstance(cls(), D)
Example #3
Source File: test_make.py From attrs with MIT License | 6 votes |
def test_metadata_present(self, list_of_attrs): """ Assert dictionaries are copied and present. """ C = make_class("C", dict(zip(gen_attr_names(), list_of_attrs))) for hyp_attr, class_attr in zip(list_of_attrs, fields(C)): if hyp_attr.metadata is None: # The default is a singleton empty dict. assert class_attr.metadata is not None assert len(class_attr.metadata) == 0 else: assert hyp_attr.metadata == class_attr.metadata # Once more, just to assert getting items and iteration. for k in class_attr.metadata: assert hyp_attr.metadata[k] == class_attr.metadata[k] assert hyp_attr.metadata.get(k) == class_attr.metadata.get( k )
Example #4
Source File: test_make.py From attrs with MIT License | 6 votes |
def test_convert_property(self, val, init): """ Property tests for attributes using converter. """ C = make_class( "C", { "y": attr.ib(), "x": attr.ib( init=init, default=val, converter=lambda v: v + 1 ), }, ) c = C(2) assert c.x == val + 1 assert c.y == 2
Example #5
Source File: test_make.py From attrs with MIT License | 6 votes |
def test_converter_factory_property(self, val, init): """ Property tests for attributes with converter, and a factory default. """ C = make_class( "C", ordered_dict( [ ("y", attr.ib()), ( "x", attr.ib( init=init, default=Factory(lambda: val), converter=lambda v: v + 1, ), ), ] ), ) c = C(2) assert c.x == val + 1 assert c.y == 2
Example #6
Source File: test_make.py From attrs with MIT License | 6 votes |
def test_run_validators(self): """ Setting `_run_validators` to False prevents validators from running. """ _config._run_validators = False obj = object() def raiser(_, __, ___): raise Exception(obj) C = make_class("C", {"x": attr.ib(validator=raiser)}) c = C(1) validate(c) assert 1 == c.x _config._run_validators = True with pytest.raises(Exception): validate(c) with pytest.raises(Exception) as e: C(1) assert (obj,) == e.value.args
Example #7
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_frozen(self): """ Converters circumvent immutability. """ C = make_class( "C", {"x": attr.ib(converter=lambda v: int(v))}, frozen=True ) C("1")
Example #8
Source File: process.py From xarray-simlab with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _make_process_subclass(self): p_cls = attr.make_class( self._base_cls.__name__, self._reset_attributes(), bases=(self._base_cls,), init=False, repr=False, ) setattr(p_cls, "__init__", _process_cls_init) setattr(p_cls, "__repr__", repr_process) setattr(p_cls, "__xsimlab_process__", True) setattr(p_cls, "__xsimlab_executor__", _ProcessExecutor(p_cls)) return p_cls
Example #9
Source File: test_roundtrips.py From cattrs with MIT License | 5 votes |
def test_simple_roundtrip_defaults(cls_and_vals, strat): """ Simple classes with metadata can be unstructured and restructured. """ a, _ = cls_and_vals cl = make_class("HypClass", {"a": a}) converter = Converter(unstruct_strat=strat) inst = cl() assert converter.unstructure( converter.structure({}, cl) ) == converter.unstructure(inst) assert inst == converter.structure(converter.unstructure(inst), cl)
Example #10
Source File: test_registry.py From excelcy with MIT License | 5 votes |
def test_exception(self): with pytest.raises(ValueError) as excinfo: TestParams5a = attr.make_class('TestParams5a', {'f1': field(0), 'f2': field()}) assert excinfo.type == ValueError with pytest.raises(ValueError) as excinfo: @attr.s() class TestParams5b(Registry): f1 = field(0) # type: int # this is not allowed f2 = field() # type: int assert excinfo.type == ValueError
Example #11
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_repr_str(self): """ Trying to add a `__str__` without having a `__repr__` raises a ValueError. """ with pytest.raises(ValueError) as ei: make_class("C", {}, repr=False, str=True) assert ( "__str__ can only be generated if a __repr__ exists.", ) == ei.value.args
Example #12
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_not_none_metadata(self, list_of_attrs): """ Non-empty metadata attributes exist as fields after ``@attr.s``. """ C = make_class("C", dict(zip(gen_attr_names(), list_of_attrs))) assert len(fields(C)) > 0 for cls_a, raw_a in zip(fields(C), list_of_attrs): assert cls_a.metadata != {} assert cls_a.metadata == raw_a.metadata
Example #13
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_empty_metadata_singleton(self, list_of_attrs): """ All empty metadata attributes share the same empty metadata dict. """ C = make_class("C", dict(zip(gen_attr_names(), list_of_attrs))) for a in fields(C)[1:]: assert a.metadata is fields(C)[0].metadata
Example #14
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_multiple_empty(self): """ Empty list/tuple for validator is the same as None. """ C1 = make_class("C", {"x": attr.ib(validator=[])}) C2 = make_class("C", {"x": attr.ib(validator=None)}) assert inspect.getsource(C1.__init__) == inspect.getsource(C2.__init__) # Hypothesis seems to cache values, so the lists of attributes come out # unsorted.
Example #15
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_propagates(self): """ The exception of the validator is handed through. """ def raiser(_, __, value): if value == 42: raise FloatingPointError C = make_class("C", {"x": attr.ib(validator=raiser)}) i = C(1) i.x = 42 with pytest.raises(FloatingPointError): validate(i)
Example #16
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_success(self): """ If the validator succeeds, nothing gets raised. """ C = make_class( "C", {"x": attr.ib(validator=lambda *a: None), "y": attr.ib()} ) validate(C(1, 2))
Example #17
Source File: typesystem.py From dkpro-cassis with Apache License 2.0 | 5 votes |
def __attrs_post_init__(self): """ Build the constructor that can create feature structures of this type """ name = _string_to_valid_classname(self.name) fields = {feature.name: attr.ib(default=None, repr=(feature.name != "sofa")) for feature in self.all_features} fields["type"] = attr.ib(default=self.name) self._constructor = attr.make_class(name, fields, bases=(FeatureStructure,), slots=True, eq=False, order=False)
Example #18
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_convert(self): """ Return value of converter is used as the attribute's value. """ C = make_class( "C", {"x": attr.ib(converter=lambda v: v + 1), "y": attr.ib()} ) c = C(1, 2) assert c.x == 2 assert c.y == 2
Example #19
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_make_class_ordered(self): """ If `make_class()` is passed ordered attrs, their order is respected instead of the counter. """ b = attr.ib(default=2) a = attr.ib(default=1) C = attr.make_class("C", ordered_dict([("a", a), ("b", b)])) assert "C(a=1, b=2)" == repr(C())
Example #20
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_missing_sys_getframe(self, monkeypatch): """ `make_class()` does not fail when `sys._getframe()` is not available. """ monkeypatch.delattr(sys, "_getframe") C = make_class("C", ["x"]) assert 1 == len(C.__attrs_attrs__)
Example #21
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_catches_wrong_attrs_type(self): """ Raise `TypeError` if an invalid type for attrs is passed. """ with pytest.raises(TypeError) as e: make_class("C", object()) assert ("attrs argument must be a dict or a list.",) == e.value.args
Example #22
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_attr_args(self): """ attributes_arguments are passed to attributes """ C = make_class("C", ["x"], repr=False) assert repr(C(1)).startswith("<tests.test_make.C object at 0x")
Example #23
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_dict(self): """ Passing a dict of name: _CountingAttr creates an equivalent class. """ C1 = make_class( "C1", {"a": attr.ib(default=42), "b": attr.ib(default=None)} ) @attr.s class C2(object): a = attr.ib(default=42) b = attr.ib(default=None) assert C1.__attrs_attrs__ == C2.__attrs_attrs__
Example #24
Source File: test_make.py From attrs with MIT License | 5 votes |
def test_simple(self, ls): """ Passing a list of strings creates attributes with default args. """ C1 = make_class("C1", ls(["a", "b"])) @attr.s class C2(object): a = attr.ib() b = attr.ib() assert C1.__attrs_attrs__ == C2.__attrs_attrs__
Example #25
Source File: test_functional.py From attrs with MIT License | 4 votes |
def test_auto_exc(self, slots, frozen): """ Classes with auto_exc=True have a Exception-style __str__, compare and hash by id, and store the fields additionally in self.args. """ @attr.s(auto_exc=True, slots=slots, frozen=frozen) class FooError(Exception): x = attr.ib() y = attr.ib(init=False, default=42) z = attr.ib(init=False) a = attr.ib() FooErrorMade = attr.make_class( "FooErrorMade", bases=(Exception,), attrs={ "x": attr.ib(), "y": attr.ib(init=False, default=42), "z": attr.ib(init=False), "a": attr.ib(), }, auto_exc=True, slots=slots, frozen=frozen, ) assert FooError(1, "foo") != FooError(1, "foo") assert FooErrorMade(1, "foo") != FooErrorMade(1, "foo") for cls in (FooError, FooErrorMade): with pytest.raises(cls) as ei1: raise cls(1, "foo") with pytest.raises(cls) as ei2: raise cls(1, "foo") e1 = ei1.value e2 = ei2.value assert e1 is e1 assert e1 == e1 assert e2 == e2 assert e1 != e2 assert "(1, 'foo')" == str(e1) == str(e2) assert (1, "foo") == e1.args == e2.args hash(e1) == hash(e1) hash(e2) == hash(e2) if not frozen: deepcopy(e1) deepcopy(e2)