My class has a method that handles an object, and passes it to another function that checks a property on that object:
class SomeObject:
def __init__(self):
self._state = 0
def change_state(self, new_state):
self._state = new_state
class MyClass:
def foo(self, o):
self._bar(o)
o.change_state(1)
self._baz = o
self._bar(o)
def _bar(self, x):
assert x._state == 0
if __name__ == '__main__':
o = SomeObject()
c = MyClass()
c.foo(o)
What _bar
should be?
- staticmethod
- function
- regular method
- other
?
I didn’t find good guidelines on what to use, so according to the following rules of thumb (shown bellow), I thought a regular method is best. The pros and cons in my head are basically these:
- method means this function should be called only by this class / instance, and won’t be mistaken as a global function. Good for readability
- method is the default way calling something when I have an instance. Again, good for readability
- staticmethod blocks users from altering the state. A good thing, but this is python – (see we are all consenting adults). Strict and defensive – not sure if that’s a good thing or not in python
- method is a good way to access the instance members. When not accessing (or even when accessing is not a good idea) – should we really use methods?
Rules of thumb I considered:
- pep 20, AKA The Zen of Python, specifically “Simple is better than complex.”
- the code style, specifically
We are all consenting adults
As seen above, Python allows many tricks, and some of them are potentially dangerous. A good example is that any client code can override an object’s properties and methods: there is no “private” keyword in Python. This philosophy, very different from highly defensive languages like Java, which give a lot of mechanisms to prevent any misuse, is expressed by the saying: “We are consenting adults”.
So, is there another rule of thumb that can help deceide between the alternatives?
7