I have a dictionary like class with methods that return views of its keys, values and items. The methods for doing this are about as simple as you can get:
class MyType(collections.MutableMapping):
def keys(self):
return collections.KeysView(self)
However, this seems pointless to create a method for something so simple; all I am doing is passing self
onto yet another callable. I would prefer to simply treat the class constructor for KeysView
as a bound method. Doing the following creates a nested class (which is good because sometimes that is exactly what you want), but it looks closer to what I would want to do:
class MyType(collections.MutableMapping):
keys = collections.KeysView
Is there anything builtin to Python or its standard library to do this? Maybe something like this:
class MyType(collections.MutableMapping):
keys = bind_constructor_as_method(collections.KeysView)
I feel like there should be something in functools
that would do the job, but there isn't anything that pops out as the right answer at first look. Maybe functools.partial
, but the name isn't very descriptive of what I'm trying to do.
Will I just need to hand roll a custom descriptor class to make something like this work?
NOTE:
For work I often need to use Python 2.7, so although Python 3.x answers are still appreciated (and useful), they probably won't totally mitigate the issue for me personally. However, they may help someone else with this question, so please still include them!