Python – Makes property methods callable

Makes property methods callable… here is a solution to the problem.

Makes property methods callable

I have a class with property methods :

class SomeClass(object):

@property
    def some_method(self):

return True

I want to call some_method and store it as an expression.

For example:

some_expr = SomeClass().some_method

The value True should not be stored in the some_expr; Instead, the expression SomeClass() should be stored so that it can be called.some_method

How do I do this?

Solution

Note that you essentially want to use a callable .__get__ on a property instance. However, this requires an instance as the first parameter, so you can only partially apply some instances:

In [6]: class SomeClass(object):
   ...:
   ...:     @property
   ...:     def some_method(self):
   ...:
   ...:         return True
   ...:

In [7]: from functools import partial

And then something like this:

In [9]: some_exp = partial(SomeClass.some_method.__get__, SomeClass())

In [10]: some_exp()
Out[10]: True

Related Problems and Solutions