Search code examples
pythoncoding-style

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


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.


Solution

  • 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.