Prevent using instancemethod function in Python 2

I am writing 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 like it to simply print personal things, 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, this is not real code, but a simplification of the real thing. I wanted to do it like this because I need to pass on private information that I do not want to expose the end user, that is, anyone who extends my classes. But in Python 2, the global level of lambda (or any simple function) becomes instancemethod, which in this case is undesirable!

What would you advise me to make this piece of code portable?

+4
source share
2

:

class MyClass(ParentClass):
    bar = staticmethod(foo)

. staticmethod "", , ( , , bar foo). >

+8

. ( , Alex Martelli), Python 2.7 3.x( , , , , , ):

, . , - , print lambda 2.x.

foo = lambda x: x            # note that you cannot use print here in 2.x

class MyClass(object):

    @staticmethod            # use a static method
    def bar(x):
        return foo(x)        # or simply print(foo(x))

    def mymethod(self):
        return self.bar(1)

>>> m = MyClass()
>>> m.mymethod()
1
+4

Source: https://habr.com/ru/post/1569645/


All Articles