uday uday - 1 month ago 13
Python Question

how to check if a variable is a property

Suppose there is a class with a

@property
defined:

class MyClass:
...
@property
def this_is_a_property(self):
return self.some_thing
...
def this_is_a_function(self, x):
...
return other_thing


Normally, to check whether an attribute is a function, I can use
isfunction
from the
inspect
module.

import inspect
if inspect.isfunction(MyClass.__dict__['this_is_a_function']):
print('this_is_a_function',' is a function')


How can I check a
property
? There appears to be no
inspect.isproperty
function.

Answer Source

Simply check the type against the property object:

if isinstance(MyClass.this_is_a_property, property):

You don't really have to retrieve it from the class dictionary here; looking up a property on the class as an attribute also returns the property instance.