Bunyk
Bunyk

Reputation: 8067

Python property returns constant

I'm seeing code like this:

@property
def entity_class(self):
    return 'common'

As all that it does - it returns a constant value, I am thinking if I could replace it with this:

entity_class = 'common'

But I have small doubt that such change could break something. Will this change have some consequences apart from making entity_class writable? Why someone would need to disallow changes to attribute?

Upvotes: 0

Views: 77

Answers (2)

minboost
minboost

Reputation: 2563

I wouldn't change it.

I've seen lots of bugs added by trivial changes such as this.

Yes, it might error either way if you try to set it in the future, but if you leave it a property it will error in a very understandable way. If you make it writable, it can be set in a way where the errors will appear in seemingly unrelated areas, making it much harder to track down.

Once you change it, it's also not clear that it is not intended to be changed.

If you want to change it, all you're doing is saving 2 lines of code.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124818

You can safely replace the property with a class attribute, yes.

The only thing that would break is code that expects ClassObject.entity_class to return a property object rather than the constant value. Instance attribute access is unchanged.

Of course, you can now set that attribute on the instance, where with the property object you couldn't. Your code may break if someone does this, but so does code that would try and set ClassObject.entity_class (thus replacing the property object). For code with a good test suite, that should not really be a problem though.

Upvotes: 1

Related Questions