Search code examples
pythonpropertiesscopedecoratornaming

Using 'property' as the name of a method in a python class


Is this possible in Python?

class MyClass(object):
    @property
    def property(self):
        return self._property

That is, I want to have a property named 'property'. It actually runs fine, but Eclipse complains with a warning. I thought the built-in @property decorator lived in a different namespace than the methods and properties within my classes.

Is it possible to rename the built-in decorator within the scope of the relevant module, so I can use the name 'property' without receiving this warning? Maybe something like the following:

attr = property

class MyClass(object):
    @attr
    def property(self):
        return self._property

I do this, but I still get the warning, since I created an alias for the global built-in @property decorator, but the name 'property' is still a valid way to refer to it.

Any ideas?


Solution

  • The problem with naming a property property is the following:

    class Foo(object):
        @property
        def property(self):
            return "ham"
    
        @property
        def other_property(self):
            return "spam"
    

    The second property can't be defined since you've shadowed the name property in the class definition.

    You can get around this by "renaming" property as in your example, but if I were you, I wouldn't mess with the built-ins in this way. It makes your code harder to follow.