Should I use get_/set_ prefixes in Python method names?

Question:

In Python, properties are used instead of the Java-style getters and setters. So one rarely sees get... or set... methods in the public interfaces of classes.

But, in cases where a property is not appropriate, one might still end up with methods that behave like getters or setters. Now for my questions: Should these method names start with get_ / set_? Or, is this unpythonic verbosity since it is often obvious of what is meant (and one can still use the docstring to clarify non-obvious situations)?

This might be a matter of personal taste, but I would be interested in what the majority thinks about this. What would you prefer as an API user?

For example, say we have an object representing multiple cities. One might have a method get_city_by_postalcode(postalcode) or one could use the shorter method city_by_postalcode. I tend towards the latter.

Asked By: nikow

||

Answers:

I think shorter is better, so I tend to prefer the latter. But what’s important is to be consistent within your project: don’t mix the two methods. If you jump into someone else’s project, keep what the other developers chose initially.

Answered By: Oli

I’ve seen it done both ways. Coming from an Objective-C background, I usually do foo()/set_foo() if I can’t use a property (although I try to use properties whenever possible). It doesn’t really matter that much, though, as long as you’re consistent.

(Of course, in your example, I wouldn’t call the method get_city_by_postalcode() at all; I’d probably go with translate_postalcode or something similar that uses a better action verb in the name.)

Answered By: mipadi

You won’t ever lose the chance to make your property behave like a getter/setter later by using descriptors. If you want to change a property to be read-only, you can also replace it with a getter method with the same name as the property and decorate it with @property. So, my advice is to avoid getters/setters unless the project you are working on already uses them because you can always change your mind later and make properties read-only, write-only, or whatever without modifying the interface to your class.

Answered By: Vasil

If it’s usable as a property (one value to get or set, and no other parameters, I usually do:

class Foo(object):

    def _get_x(self):
        pass

    def _set_x(self, value):
        pass

    x = property(_get_x, _set_x)

If the getter/setter is any more complex than that, I would use get_x and set_x:

Answered By: Jeremy Cantrell

If I have to use a getter/setter, I like it this way:

Suppose you have a variable self._x. Then x() would return the value of self._x, and setX(x) would set the value of self._x

Answered By: user44484
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.