This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Adding __getitem__ as a class method doesn't work as expected
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: eric.snow, samwyse
Priority: normal Keywords:

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 <module>
    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:32adminsetgithub: 59494
2012-07-10 14:48:09samwysesetfiles: + Issue15289.py

messages: + msg165192
2012-07-07 20:37:42eric.snowsetstatus: open -> closed
resolution: not a bug
components: + Interpreter Core, - None
stage: resolved
2012-07-07 20:32:32eric.snowsetnosy: + eric.snow
messages: + msg164935
2012-07-07 19:47:57samwysecreate