0

I'm trying to make a function object subscriptable in Python. That is, I do not want to create a wrapper class for the function in order to do this.

I'm trying to do this via the follolwing:

import types
def func(): pass
def func_getitem(*args): print(args)
func.__getitem__ = types.MethodType(func_getitem, func)

If I do:

func.__getitem__()

It works fine, and prints (self,); but trying:

func[0]

Raises TypeError: 'function' object is not subscriptable.

The python 3 docs says:

object.__getitem__(self, key)

Called to implement evaluation of self[key].

So I'd expect the latter example to work correctly, but it does not.

I originally thought it may have to do with bound and unbound methods, but, unless I am missing something, types.MethodType should take care of that.

Quelklef
  • 1,999
  • 2
  • 22
  • 37
  • I'm just wondering: Why? – tyteen4a03 Jun 19 '17 at 21:17
  • @tyteen4a03 Why put `__getitem__` on a function? For fancy syntax. Why not use a class? I could, but at this point I also want to learn why this way doesn't work. – Quelklef Jun 19 '17 at 21:18
  • 2
    Because you're adding the magic method to an instance (the specific function), not the class (of functions generally). See e.g. https://stackoverflow.com/a/34443595/3001761. Using a class of your own will be much easier than trying to patch up functions, just implement `__getitem__` and `__call__`. – jonrsharpe Jun 19 '17 at 21:21

0 Answers0