I often use dict
to group and namespace related data. Two drawbacks are:
- I cannot type-hint individual entries (e.g.
x['s']: str = ''
). Accessing union-typed values (e.g.x: dict[str, str | None] = {}
) later needsassert
statements to please mypy. - Spelling entries is verbose. Values mapped to
str
keys need four extra characters (i.e.['']
); attributes only need one (i.e..
).
I've considered types.SimpleNamespace
. However, like with classes, I run into this mypy error:
import types
x = types.SimpleNamespace()
x.s: str = ''
# 3 col 2 error| Type cannot be declared in assignment to non-self attribute [python/mypy]
- Is there a way to type-hint attributes added after instantiation?
- If not, what other structures should I consider? As with
dict
and unlikecollections.namedtuple
, I require mutability.