Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a function from becoming an instancemethod in Python 2

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?

like image 682
jleeothon Avatar asked Dec 15 '22 17:12

jleeothon


1 Answers

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).

like image 121
Alex Martelli Avatar answered Apr 28 '23 13:04

Alex Martelli