Mokus
Mokus

Reputation: 10400

Python constants declaration

if I declare a const class which are contains variables:

for example

class const:
    MASTER_CLIENT_CONNECTED = 0
    CLIENT_CONNECTED = 1        
    GET_SERVER_QUEUE = 9998    
    ERROR = 9999

is there any way to reach this variable(constants) without creating a new class.

like this:

import const
const.MASTER_CLIENT_CONNECTED 

or

import const
if(i==MASTER_CLIENT_CONNECTED):

Upvotes: 9

Views: 28247

Answers (3)

Sarthak Ahuja
Sarthak Ahuja

Reputation: 85

In the above solutions the only drawback is that you can accidentally modify the variables in the const.py file -

#const.py
var_a = 1

#app.py
import const
print(const.var)
const.var = 2
print(const.var)

#output
1
2

This maybe a hacky solution, but to prevent modification of any constant variable, you can add them to a class with only getter methods.

#const.py
class Constants:
    @classmethod
    get_vara(cls):
        return 1


#app.py
from const import Constants
print(Constants.get_vara())

#output
1

I know that this method may crowd up the const.py file, but this is the only solution I know which in true definition exemplifies immutability.

Upvotes: 0

sam
sam

Reputation: 19164

Why do you need a class for that? You can use something like this:

In constant.py write:

MASTER_CLIENT_CONNECTED = 0
CLIENT_CONNECTED = 1        
GET_SERVER_QUEUE = 9998    
ERROR = 9999

Then access it as:

import constant
print constant.MASTER_CLIENT_CONNECTED
print constant.CLIENT_CONNECTED 
print constant.GET_SERVER_QUEUE 
print constant.GET_SERVER_QUEUE 

Upvotes: 5

ThiefMaster
ThiefMaster

Reputation: 318458

Yes, instead of putting them in a class put them directly into your module (name the file e.g. const.py so the module name is const). Using a class for this is pretty much abusing classes for namespacing - and Python has packages/modules for this purpose.

Then you could even use from const import * to import all globals from this module if you don't want to write const. in front of everything. However note that this is usually discouraged as it potentially imports lots of things into the global namespace - if you just need one or two constants from const import ABC, DEF etc. would be fine though.

Upvotes: 12

Related Questions