I'm working on a python class which has a valid meaning for the index operator ([]
or __getitem__()
if you would prefer) at both the class and instance level. Specifically indexing strings is valid. As such I would like to implement a dictionary interface for both levels. The __class_getitem__()
method solves this problem for the []
operator; However, I will still need other methods such as keys()
, __contains__()
, __len__()
etc to behave differently if you for example call cls.keys()
vs cls().keys()
.
I'm fairly sure this can be done by using some combination of __getattr__()
/ __getattribute__()
overloads and some tricky closure shenanigans. However, I would strongly like avoid doing so if at all reasonible for the following reasons:
- doings so is terribly clunky
- its confusing to non-expert coders
- hard to see and parse to the point of potentially blindsiding expert coders
- Tools like PyCharm's code completion system can't see that kind of stuff.
I suspect that the best answer will probably involve using a metaclass which I'm a bit resigned to but hope there is a clever way to avoid maybe through argument type detection and a decorator or something. (a subclass of classmethod
which has a instancemethod
attribute which gets called in the case of not isinstance(cls, type)
maybe?)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…