Home > Net >  Is there a good way in Python to create containers for constants
Is there a good way in Python to create containers for constants

Time:01-09

I am looking for a pythonic way to represent containers of constants. The constants are accessed as attributes so that the IDE can auto-complete as necessary. Currently I use simple classes with class attributes:

class CONFIG():
    DIR = 'C:'
    VERSION = '2.0'

# usage:
version = CONFIG.VERSION

The class is used as an object, never instantiated, the constants are static class attributes. Of course, they can be messed with, and that's one problem.

Is there a better way to do this? NamedTuples do not have the flexibility and clarity to add new constants on the fly, unless I miss something.

CodePudding user response:

If you are concerned with the values being overwritten at some point in your code base, you could try using a class property.

class Config:
    @classmethod
    @property
    def dir(cls) -> str:
        return "C://"

This cannot be overwritten accidentally and your IDE will help you with autocompletion. However, it is rather verbose code.

CodePudding user response:

[not really an answer]

When you should use configs class. lets have the following example.

class Game:

    CRICKET = 1
    FOOTBALL = 2
    BADMINTON = 3
    TENNIS = 4
    VOLLEYBALL = 5

    GAME_CHOICES = (
        (CRICKET, 'Cricket'),
        (FOOTBALL, 'Football'),
        (BADMINTON, 'Badminton'),
        (TENNIS, 'Tennis'),
        (VOLLEYBALL, 'Volleyball'),
    )

print(Game.CRICKET) #1

such structure comes handy when you have sort of choices to do something. such as there could be a field in your DB model that you would like to give a choice. you can add following in model class

 game_choice = models.IntegerField(
        choices=GAME_CHOICES, default=CRICKET, db_index=True)
  •  Tags:  
  • Related