Is there a way to check if a property has a setter?

Viewed 460

Is there a way in Python 3.X to check if a class defines a setter method for one of its properties?

Let's say I have the following example :

class Test:
  def __init__(self):
    self._p = None

  @property
  def my_property(self):
    return self._p

  @my_property.setter
  def my_property(self, new_value):
    self._p = new_value

I can check if my_property is defined with hasattr but I can't find a way to check if the setter is defined.

Here are the two avenues I considered without success :

  1. Using hasattr to find if a method named my_property.setter or something like that exists.
  2. Using the inspect.signature function to see if the method my_property has 2 parameters (self and new_value).

I guess that an extended answer to this question would consider how to detect the presence of a getter as well (making the difference between a property and a getter method because callable(test.my_property) returns False when we might think it should be True because it is a method).

1 Answers

You can test if the .fset attribute is None or not:

>>> Test.my_property.fset is not None  # has a setter
True
>>> Test.my_property.fdel is not None  # has no deleter
False

The same way you can also test if it has a getter (via .fget). To test whether the attribute is a property at all, you can test isinstance(Test.my_property, property).

Make sure to always call these on the class level, and not on an individual instance.

Related