Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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):
like image 407
OHLÁLÁ Avatar asked Jun 20 '11 09:06

OHLÁLÁ


People also ask

Can you declare constants in Python?

You cannot declare a variable or value as constant in Python.

What is constant declaration 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.

Can you declare constants?

Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero. A program that demonstrates the declaration of constant variables in C using const keyword is given as follows.


1 Answers

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.

like image 129
ThiefMaster Avatar answered Sep 18 '22 07:09

ThiefMaster