Issue 15289: Adding getitem as a class method doesn't work as expected (original) (raw)

Issue15289

Created on 2012-07-07 19:47 by samwyse, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
20120607.py samwyse,2012-07-07 19:47 demonstrates the behavior
Issue15289.py samwyse,2012-07-10 14:48 implements the desired behavior
Messages (3)
msg164926 - (view) Author: Samwyse (samwyse) * Date: 2012-07-07 19:47
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__'
msg164935 - (view) Author: Eric Snow (eric.snow) * (Python committer) Date: 2012-07-07 20:32
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-names http://docs.python.org/py3k/library/inspect.html#fetching-attributes-statically
msg165192 - (view) Author: Samwyse (samwyse) * Date: 2012-07-10 14:48
Thanks, Eric. Based on what you said, I was able to get the desired behavior by creating a metaclass.
History
Date User Action Args
2022-04-11 14:57:32 admin set github: 59494
2012-07-10 14:48:09 samwyse set files: + Issue15289.pymessages: +
2012-07-07 20:37:42 eric.snow set status: open -> closedresolution: not a bugcomponents: + Interpreter Core, - Nonestage: resolved
2012-07-07 20:32:32 eric.snow set nosy: + eric.snowmessages: +
2012-07-07 19:47:57 samwyse create