Python attr.astuple() Examples

The following are 26 code examples of attr.astuple(). 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_tables.py    From tskit with MIT License 6 votes vote down vote up
def test_simple_example(self):
        t = tskit.NodeTable()
        t.add_row(flags=0, time=1, population=2, individual=0, metadata=b"123")
        t.add_row(flags=1, time=2, population=3, individual=1, metadata=b"\xf0")
        s = str(t)
        self.assertGreater(len(s), 0)
        self.assertEqual(len(t), 2)
        self.assertEqual(attr.astuple(t[0]), (0, 1, 2, 0, b"123"))
        self.assertEqual(attr.astuple(t[1]), (1, 2, 3, 1, b"\xf0"))
        self.assertEqual(t[0].flags, 0)
        self.assertEqual(t[0].time, 1)
        self.assertEqual(t[0].population, 2)
        self.assertEqual(t[0].individual, 0)
        self.assertEqual(t[0].metadata, b"123")
        self.assertEqual(t[0], t[-2])
        self.assertEqual(t[1], t[-1])
        self.assertRaises(IndexError, t.__getitem__, -3) 
Example #2
Source File: test_tables.py    From tskit with MIT License 6 votes vote down vote up
def test_simple_example(self):
        t = tskit.SiteTable()
        t.add_row(position=0, ancestral_state="1", metadata=b"2")
        t.add_row(1, "2", b"\xf0")
        s = str(t)
        self.assertGreater(len(s), 0)
        self.assertEqual(len(t), 2)
        self.assertEqual(attr.astuple(t[0]), (0, "1", b"2"))
        self.assertEqual(attr.astuple(t[1]), (1, "2", b"\xf0"))
        self.assertEqual(t[0].position, 0)
        self.assertEqual(t[0].ancestral_state, "1")
        self.assertEqual(t[0].metadata, b"2")
        self.assertEqual(t[0], t[-2])
        self.assertEqual(t[1], t[-1])
        self.assertRaises(IndexError, t.__getitem__, 2)
        self.assertRaises(IndexError, t.__getitem__, -3) 
Example #3
Source File: test_tables.py    From tskit with MIT License 6 votes vote down vote up
def test_simple_example(self):
        t = tskit.MutationTable()
        t.add_row(site=0, node=1, derived_state="2", parent=3, metadata=b"4")
        t.add_row(1, 2, "3", 4, b"\xf0")
        s = str(t)
        self.assertGreater(len(s), 0)
        self.assertEqual(len(t), 2)
        self.assertEqual(attr.astuple(t[0]), (0, 1, "2", 3, b"4"))
        self.assertEqual(attr.astuple(t[1]), (1, 2, "3", 4, b"\xf0"))
        self.assertEqual(t[0].site, 0)
        self.assertEqual(t[0].node, 1)
        self.assertEqual(t[0].derived_state, "2")
        self.assertEqual(t[0].parent, 3)
        self.assertEqual(t[0].metadata, b"4")
        self.assertEqual(t[0], t[-2])
        self.assertEqual(t[1], t[-1])
        self.assertRaises(IndexError, t.__getitem__, -3) 
Example #4
Source File: test_tables.py    From tskit with MIT License 6 votes vote down vote up
def test_simple_example(self):
        t = tskit.MigrationTable()
        t.add_row(left=0, right=1, node=2, source=3, dest=4, time=5, metadata=b"123")
        t.add_row(1, 2, 3, 4, 5, 6, b"\xf0")
        self.assertEqual(len(t), 2)
        self.assertEqual(attr.astuple(t[0]), (0, 1, 2, 3, 4, 5, b"123"))
        self.assertEqual(attr.astuple(t[1]), (1, 2, 3, 4, 5, 6, b"\xf0"))
        self.assertEqual(t[0].left, 0)
        self.assertEqual(t[0].right, 1)
        self.assertEqual(t[0].node, 2)
        self.assertEqual(t[0].source, 3)
        self.assertEqual(t[0].dest, 4)
        self.assertEqual(t[0].time, 5)
        self.assertEqual(t[0].metadata, b"123")
        self.assertEqual(t[0], t[-2])
        self.assertEqual(t[1], t[-1])
        self.assertRaises(IndexError, t.__getitem__, -3) 
Example #5
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 #6
Source File: test_tables.py    From tskit with MIT License 5 votes vote down vote up
def test_simple_example(self):
        t = tskit.PopulationTable()
        t.add_row(metadata=b"\xf0")
        t.add_row(b"1")
        s = str(t)
        self.assertGreater(len(s), 0)
        self.assertEqual(len(t), 2)
        self.assertEqual(attr.astuple(t[0]), (b"\xf0",))
        self.assertEqual(t[0].metadata, b"\xf0")
        self.assertEqual(attr.astuple(t[1]), (b"1",))
        self.assertRaises(IndexError, t.__getitem__, -3) 
Example #7
Source File: test_renderer.py    From corrscope with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def all_colors_to_str(val) -> Optional[str]:
    """Called once for each `appear` and `data`."""

    if isinstance(val, Appearance):
        args_tuple = attr.astuple(val, recurse=False)
        return f"appear=Appearance{args_tuple}"

    if isinstance(val, np.ndarray):
        data_type = "stereo" if val.shape[1] > 1 else "mono"
        return "data=" + data_type

    raise ValueError("Unrecognized all_colors parameter, not `appear` or `data`") 
Example #8
Source File: test_unstructure.py    From cattrs with MIT License 5 votes vote down vote up
def test_attrs_astuple_unstructure(nested_class):
    """Our dumping should be identical to `attrs`."""
    converter = Converter(unstruct_strat=UnstructureStrategy.AS_TUPLE)
    instance = nested_class[0]()
    assert converter.unstructure(instance) == astuple(instance) 
Example #9
Source File: test_structure_attrs.py    From cattrs with MIT License 5 votes vote down vote up
def test_structure_tuple(converter, cl_and_vals):
    """Test loading from a tuple, by registering the loader."""
    cl, vals = cl_and_vals
    converter.register_structure_hook(cl, converter.structure_attrs_fromtuple)
    obj = cl(*vals)

    dumped = astuple(obj)
    loaded = converter.structure(dumped, cl)

    assert obj == loaded 
Example #10
Source File: test_funcs.py    From attrs with MIT License 5 votes vote down vote up
def test_roundtrip(self, cls, tuple_class):
        """
        Test dumping to tuple and back for Hypothesis-generated classes.
        """
        instance = cls()
        tuple_instance = astuple(instance, tuple_factory=tuple_class)

        assert isinstance(tuple_instance, tuple_class)

        roundtrip_instance = cls(*tuple_instance)

        assert instance == roundtrip_instance 
Example #11
Source File: test_funcs.py    From attrs with MIT License 5 votes vote down vote up
def test_dicts_retain_type(self, container, C):
        """
        If recurse and retain_collection_types are True, also recurse
        into lists and do not convert them into list.
        """
        assert (1, container({"a": (4, 5)})) == astuple(
            C(1, container({"a": C(4, 5)})), retain_collection_types=True
        ) 
Example #12
Source File: test_funcs.py    From attrs with MIT License 5 votes vote down vote up
def test_lists_tuples_retain_type(self, container, C):
        """
        If recurse and retain_collection_types are True, also recurse
        into lists and do not convert them into list.
        """
        assert (1, container([(2, 3), (4, 5), "a"])) == astuple(
            C(1, container([C(2, 3), C(4, 5), "a"])),
            retain_collection_types=True,
        ) 
Example #13
Source File: test_funcs.py    From attrs with MIT License 5 votes vote down vote up
def test_dicts(self, C, tuple_factory):
        """
        If recurse is True, also recurse into dicts.
        """
        res = astuple(C(1, {"a": C(4, 5)}), tuple_factory=tuple_factory)
        assert tuple_factory([1, {"a": tuple_factory([4, 5])}]) == res
        assert isinstance(res, tuple_factory) 
Example #14
Source File: test_funcs.py    From attrs with MIT License 5 votes vote down vote up
def test_filter(self, C, tuple_factory):
        """
        Attributes that are supposed to be skipped are skipped.
        """
        assert tuple_factory([tuple_factory([1])]) == astuple(
            C(C(1, 2), C(3, 4)),
            filter=lambda a, v: a.name != "y",
            tuple_factory=tuple_factory,
        ) 
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(self, C, tuple_factory):
        """
        Deep astuple returns correct tuple.
        """
        assert tuple_factory(
            [tuple_factory([1, 2]), tuple_factory([3, 4])]
        ) == astuple(C(C(1, 2), C(3, 4)), tuple_factory=tuple_factory) 
Example #17
Source File: test_funcs.py    From attrs with MIT License 5 votes vote down vote up
def test_shallow(self, C, tuple_factory):
        """
        Shallow astuple returns correct dict.
        """
        assert tuple_factory([1, 2]) == astuple(
            C(x=1, y=2), False, tuple_factory=tuple_factory
        ) 
Example #18
Source File: generate_vectors.py    From python-shamir-mnemonic with MIT License 5 votes vote down vote up
def decode_mnemonic(mnemonic):
    return list(attr.astuple(Share.from_mnemonic(mnemonic))) 
Example #19
Source File: test_tables.py    From tskit with MIT License 5 votes vote down vote up
def test_simple_example(self):
        t = tskit.EdgeTable()
        t.add_row(left=0, right=1, parent=2, child=3, metadata=b"123")
        t.add_row(1, 2, 3, 4, b"\xf0")
        self.assertEqual(len(t), 2)
        self.assertEqual(attr.astuple(t[0]), (0, 1, 2, 3, b"123"))
        self.assertEqual(attr.astuple(t[1]), (1, 2, 3, 4, b"\xf0"))
        self.assertEqual(t[0].left, 0)
        self.assertEqual(t[0].right, 1)
        self.assertEqual(t[0].parent, 2)
        self.assertEqual(t[0].child, 3)
        self.assertEqual(t[0].metadata, b"123")
        self.assertEqual(t[0], t[-2])
        self.assertEqual(t[1], t[-1])
        self.assertRaises(IndexError, t.__getitem__, -3) 
Example #20
Source File: manifest.py    From parsec-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def __eq__(self, other: object) -> bool:
        if isinstance(other, int):
            return self.start.__eq__(other)
        if isinstance(other, Chunk):
            return attr.astuple(self).__eq__(attr.astuple(other))
        raise TypeError

    # Properties 
Example #21
Source File: base.py    From parsec-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def __eq__(self, other: "BaseData") -> bool:
        if isinstance(other, type(self)):
            return attr.astuple(self).__eq__(attr.astuple(other))
        return NotImplemented 
Example #22
Source File: base.py    From parsec-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def __eq__(self, other: "BaseSignedData") -> bool:
        if isinstance(other, type(self)):
            return attr.astuple(self).__eq__(attr.astuple(other))
        return NotImplemented 
Example #23
Source File: core.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def __iter__(self):
    return iter(attr.astuple(self, recurse=False)) 
Example #24
Source File: core.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def to_jsonable(self):
    return attr.astuple(self)

  # Allow HistoryItems to act like tuples for unpacking. 
Example #25
Source File: measured_process_test.py    From federated with Apache License 2.0 5 votes vote down vote up
def test_constructor_with_state_only(self):
    ip = measured_process.MeasuredProcess(
        _build_initialize_comp(0), count_int32)

    state = ip.initialize()
    iterations = 10
    for _ in range(iterations):
      state, result, measurements = attr.astuple(ip.next(state))
      self.assertLen(result, 0)
      self.assertLen(measurements, 0)
    self.assertEqual(state, iterations) 
Example #26
Source File: langserver.py    From ffi-navigator with Apache License 2.0 5 votes vote down vote up
def pattern2loc(pattern_list):
    results = []
    dupset = set()
    proc = lambda decl: lsp.Location(uri=path2uri(decl.path), range=decl.range)
    for x in pattern_list:
        x = proc(x)
        key = attr.astuple(x)
        if key not in dupset:
            dupset.add(key)
            results.append(attr.asdict(x))
    return results