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 needsassertstatements to please mypy. - Spelling entries is verbose. Values mapped to
strkeys 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
dictand unlikecollections.namedtuple, I require mutability.