UnionDict
– a dict with set like operations and keys as attributes#
This object combines the key-element storage of a dict
with the union operation of a set()
object. It is used in the cogent3.draw
module, primarily for the figure
and layout
attributes.
Accessing elements of a UnionDict
#
Keys in a UnionDict
can be accessed like attributes
from cogent3.util.union_dict import UnionDict
data = UnionDict(a=2, b={"c": 24, "d": [25]})
data.a
2
data["a"]
2
data.b.d
[25]
Updating a UnionDict
#
If you use the |
bitwise operator to compare two dicts and the left one is a UnionDict
, a union operation is performed.
from cogent3.util.union_dict import UnionDict
data = UnionDict(a=2, b={"c": 24, "d": [25]})
data.b |= {"d": 25}
data.b
{'c': 24, 'd': 25}
This can also be done using the union
method.
data.b.union({"d": [25]})
data.b
{"c": 24, "d": [25]}
{'c': 24, 'd': [25]}
Accessing a non-existent UnionDict
key#
from cogent3.util.union_dict import UnionDict
data = UnionDict(a=2, b={"c": 24, "d": [25]})
data["k"]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[7], line 4
1 from cogent3.util.union_dict import UnionDict
3 data = UnionDict(a=2, b={"c": 24, "d": [25]})
----> 4 data["k"]
KeyError: 'k'
But if accessing as an attribute, you get an attribute error.
data.k
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
File ~/miniconda3/envs/c3docs/lib/python3.11/site-packages/cogent3/util/union_dict.py:36, in UnionDict.__getattr__(self, item)
35 try:
---> 36 return super().__getattr__(item)
37 except AttributeError:
AttributeError: 'super' object has no attribute '__getattr__'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
Cell In[8], line 1
----> 1 data.k
File ~/miniconda3/envs/c3docs/lib/python3.11/site-packages/cogent3/util/union_dict.py:38, in UnionDict.__getattr__(self, item)
36 return super().__getattr__(item)
37 except AttributeError:
---> 38 raise AttributeError(f"'{item}' not a key or attribute")
AttributeError: 'k' not a key or attribute