Which of the following two approaches is considered best practice? The both achieve the same result.
class Foo():
LABELS = ('One','Two','Three')
class Bar():
def __init__(self):
self.__labels = ('One','Two','Three')
@property
def labels(self):
return self.__labels
If you don't need custom getting or setting behavior, there's no point in making something a property. The first version is better.
Also, these are not quite identical in their behavior. In Foo
, there's a class-level attribute for labels. In Bar
, there isn't. Referencing Foo.LABELS
will work fine, referencing Bar.labels
will throw an exception.
The PEP 8 Style Guide for Python Code offers a 3rd way, and the Zen of Python agrees.
They suggests adding a very simple module, that creates a namespace to define the constants.
Entire of contents of e.g. package/constants.py
:
LABELS = ('One', 'Two', 'Three')
Example usage:
from package.constants import LABELS
print(LABELS) # -> ('One', 'Two', 'Three')
Note that there isn't any explicit constant "protection" here. You can jump through hoops to try to get constant constants... Or you can accept that any protection you put in place can be side-stepped by someone who really wants to, then just re-quote whoever said that stuff about consenting adults and go with the very sensible notion that variables in ALL_CAPS
are properly respected by enough developers that you just shouldn't worry about enforcing your notion of constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With