I’m writing a class that has a dict containing int to method mappings. However setting the values in this dict results in the dict being populated with unbound functions.
class A:
def meth_a: ...
def meth_b: ...
...
map = {1: meth_a, 2: meth_b, ...}
for int in ...:
map[int] = meth_x
This doesn’t work for a few reasons:
- The methods aren’t bound when the class is initialized because they’re not in the class
dict? - I can’t bind the methods manually using
__get__because the class name isn’t bound to any namespace yet.
So:
- How can I do this?
- Do I have to drop out of the class and define the dict after the class has been initialized?
- Is it really necessary to call
__get__on the methods to bind them?
Update0
The methods will be called like this:
def func(self, int):
return self.map[int]()
Also regarding the numeric indices/list: Not all indices will be present. I’m not aware that one can do list([1]=a, [2]=b, [1337]=leet) in Python, is there an equivalent? Should I just allocate a arbitrary length list and set specific values? The only interest I have here is in minimizing the lookup time, would it really be that different to the O(1) hash that is {}? I’ve ignored this for now as premature optimization.
I’m not sure exactly why you’re doing what you’re doing, but you certainly can do it right in the class definition; you don’t need
__init__.An “unbound” instance method simply needs you to pass it an instance of the class manually, and it works fine.
Also, please don’t use
intas the name of a variable, either, it’s a builtin too.A dictionary is absolutely the right type for this kind of thing.
Edit: This will also work for
staticmethods andclassmethods if you use new-style classes.