I'm using a class as a decorator, and saving information in a class variable. I wanted to access the information via a __getitem__ class method, but using conventional syntax doesn't work on a class. The following exception is thrown when the attached script is run. Traceback (most recent call last): File "/Users/sam/Documents/forth.py", line 34, in print Alias["f'"] TypeError: 'type' object has no attribute '__getitem__'
This appears to be a misunderstanding about special-method lookup which, honestly, isn't super obvious at first. It helps to remember that classes are objects like everything else in Python and thus are instances of some type (their metaclass). Anyway, here's the key point regarding special-method lookup. As far as Python is concerned, the following are equivalent: value = obj[key] and value = type(obj).__getitem__(obj, key) Thus Alias()["f'"] will give you your answer, but Alias["f'"] tries to call type(Alias).__getitem__(Alias, key). Since Alias is a class, it is an instance of the built-in type class, so type(alias) is type, which does not have a __getitem__() method. Check out the following resources: http://docs.python.org/py3k/reference/datamodel.html#special-method-nameshttp://docs.python.org/py3k/library/inspect.html#fetching-attributes-statically