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.