In Python, is there any way to declare a class-like interface with a list of attributes, other than namedtuple? I want to make a mixin from a list of attribute names. My best attempt so far is:
# module1.py (user facing)
CUSTOM_FIELDS = ['eye_color', 'shoe_size']
# module2.py (inside my framework)
from collections import namedtuple
from typing import Union
class BasePerson:
name: Any
age: Any
CustomMixin = namedtuple('CustomMixin', CUSTOM_FIELDS)
Person = Union[BasePerson, CustomMixin]
# module3.py (user facing)
def f(a: Person):
# my objective is for IDEs like PyCharm to recognize a.eye_color and a.name
a.eye_color
a.name
This is pretty close, since IDEs recognize the attributes. But it also shows all the other attributes for NamedTuple and tuple (such as _asdict
, etc).
I need users to define the attributes as a list of fields, not with regular class syntax. Firstly, for consistency with the rest of my framework. Secondly, using class syntax would open up a can of worms, since you can do all kinds of things in classes that are not permitted by my framework.
I also tried:
class CustomMixin:
__slots__ = CUSTOM_FIELDS
But PyCharm doesn't recognize this. I also looked at typing.Protocol
but it also requires declaring a class.