Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constants in Python: at the root of the module or in a namespace inside the module?

Tags:

python

People also ask

Where to place constants in Python?

In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words.

What are the constants in Python?

Constants in Python A constant is a type of variable that holds values, which cannot be changed. In reality, we rarely use constants in Python. Constants are usually declared and assigned on a different module/file.

What is difference between namespace and module in Python?

In Python-speak, modules are a namespace—a place where names are created. And names that live in a module are called its attributes. Technically, modules correspond to files, and Python creates a module object to contain all the names defined in the file; but in simple terms, modules are just namespaces.

What is the namespace in Python?

Namespaces in Python. A namespace is a collection of currently defined symbolic names along with information about the object that each name references. You can think of a namespace as a dictionary in which the keys are the object names and the values are the objects themselves.


Well, it depends. Usually, constants are defined at module level. But if you have many constants for category_a and category_b, it might even make sense to add a subpackage constants with modules constants.category_a and constants.category_b.

I would refrain from using a class - it could be instanciated, which wouldn't make sense, and it has no advantage over a module apart from allowing you to cram more than one into one physical file (which you propably shouldn't if there are so many constants). The Java version would propably use a static class, but the Python equivalent is a module.

Name clashes aren't an issue in Python except when you import * - but you shouldn't do that anyway. As long as there are no name clashes inside the module, rest assured that the user will neither pull out all the names from your module into his own nor import it under a name that clashes with another module.


Every module provides its own namespace, so there's no need to create another one.

Having module foo.py:

FOO = 1
BAR = 2
SHMOO = 3

you may use it like this:

import foo
foo.BAR

From style guide: Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.


If you use classes you can forbid overwrite of constants (or forbid even adding constants to that class). Also advantage of using class over files(modules) is when you have many groups you need not to have many files.

So it would look like this:

class MyConstBaseClass: 
    """
    forbids to overwrite existing variables 
    forbids to add new values if "locked" variable exists
    """ 
    def __setattr__(self,name,value):
        if(self.__dict__.has_key("locked")):    
            raise NameError("Class is locked can not add any attributes (%s)"%name)
        if self.__dict__.has_key(name):
            raise NameError("Can't rebind const(%s)"%name)
        self.__dict__[name]=value

class MY_CONST_GRP1(MyConstBaseClass):
    def __init__(self):
        self.const1 = "g1c1"
        self.const2 = "g1c2"
my_const_grp1 = MY_CONST_GRP1()

class MY_CONST_GRP2(MyConstBaseClass):
    def __init__(self):
        self.const1 = "g2c1"
        self.const3 = "g2c3"
        self.locked = 1 # this will create lock for adding constants 
my_const_grp2 = MY_CONST_GRP2()

print my_const_grp1.const1 # prints "g1c1" 
print my_const_grp1.const2 # prints "g1c2"
print my_const_grp2.const1 # prints "g2c1"
print my_const_grp2.const3 # prints "g2c3"
my_const_grp1.new_constant = "new value" #adding constants is allowed to this group
#my_const_grp1.const1 = "new value" #redefine would raise an error
#my_const_grp2.new_constant = "first value" #adding constant is also forbidden
#my_const_grp2.const1 = "new value" #redefine would raise an error

Here is simillar example