Another Python code style question.
If I have some "constant values" (quoted because there is not such thing in Python) that apply to a single class, what is preferred: module-level variables, or class variables?
E.g. Suppose we have a class Counter which does something when a constant threshold value is reached, which is preferred?
class Counter(object):
THRESHOLD = 6
...
def increment(self):
self.val += 1
if self.val == Counter.THRESHOLD:
do_something()
or:
COUNTER_THRESHOLD = 6
class Counter(object):
...
def increment(self):
self.val += 1
if self.val == COUNTER_THRESHOLD:
do_something()
The only thing I've managed to dig up is from the Python docs. They suggest that class variables are ideally treated as "constant":
Class variables can be used as defaults for instance variables, but using mutable values there can lead to unexpected results.
https://docs.python.org/2/reference/compound_stmts.html#class-definitions
However, this doesn't really answer the question. EDIT: As @JBernardo pointed out, this is irrelevant, as it refers to mutable data types, not to mutable variable values.
Thoughts?
Thanks
self.THRESHOLD, which will handle inheritance more neatly. Also, that quote from the docs doesn't say what you claim it does - immutability is not the same as being considered a constant.self.tip. I will leave the question a while longer to see what others think too.self.THRESHOLD, it first look for instancevarand then classvar, you can manipulate the instance varself.THRESHOLDwhile keeping class var intact