Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Should I use a Constant or a Property?

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
like image 845
Declan_K Avatar asked Mar 24 '23 11:03

Declan_K


2 Answers

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.

like image 52
Peter DeGlopper Avatar answered Apr 01 '23 21:04

Peter DeGlopper


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.

like image 31
anregen Avatar answered Apr 01 '23 19:04

anregen