I'm writing some code that works in Python 3 but not Python 2.
foo = lambda x: x + "stuff"
class MyClass(ParentClass):
bar = foo
def mymethod(self):
return self.bar(self._private_stuff)
I would want it to simply print the private stuff, but if I try to run mymethod, I get:
TypeError: unbound method <lambda>() must be called with MyClass instance as first argument (got str instance instead)
Of course, the above is not the actual code, but a simplification of the real thing. I wanted to do it like this because I need to pass along private information that I don't want to expose the final user to i.e. anybody that extends my classes. But in Python 2, the global level lambda (or any plain function) become an instancemethod
, which is unwanted in this case!
What do you recommend me to make this piece of code portable?
Simplest:
class MyClass(ParentClass):
bar = staticmethod(foo)
with the rest of your code staying the same. While staticmethod
is most often used as a "decorator", there is no requirement to do so (thus, no requirement for a further level of indirection to have bar
be a decorated method calling foo
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With