0% found this document useful (0 votes)
198 views

Constants in Python

1. In Python, there is no const keyword to declare constants. Instead, constants can be created using class properties with getter functions but no setter functions to prevent rewriting the value. 2. An example shows creating read-only class properties using a decorator that defines a getter function and raises an error in the setter. 3. Constants can also be declared as all-capital variable names according to conventions or by defining getter-only functions. Namedtuples provide another way to create immutable constant values.

Uploaded by

oraculus_lunae
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
198 views

Constants in Python

1. In Python, there is no const keyword to declare constants. Instead, constants can be created using class properties with getter functions but no setter functions to prevent rewriting the value. 2. An example shows creating read-only class properties using a decorator that defines a getter function and raises an error in the setter. 3. Constants can also be declared as all-capital variable names according to conventions or by defining getter-only functions. Namedtuples provide another way to create immutable constant values.

Uploaded by

oraculus_lunae
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

PYTHON - CONSTANTS

There's no const keyword as in other languages, however it is possible to create a


Property that has a "getter function" to read the data, but no "setter function" to
re-write the data. This essentially protects the identifier from being changed.
Here is an alternative implementation using class property:
Note that the code is far from easy for a reader wondering about constants. See
explanation below
def constant(f):
def fset(self, value):
raise SyntaxError
def fget(self):
return f()
return property(fget, fset)
class _Const(object):
@constant
def FOO():
return 0xBAADFACE
@constant
def BAR():
return 0xDEADBEEF
CONST = _Const()
print CONST.FOO
##3131964110
CONST.FOO = 0
##Traceback (most recent call last):
## ...
## CONST.FOO = 0
##SyntaxError: None

Code Explanation:
1.
Define a function constant that takes an expression, and uses it to construct
a "getter" - a function that solely returns the value of the expression.
2.
The setter function raises a SyntaxError so it's read-only
3.

Use the constant function we just created as a decoration to quickly define


read-only properties.

And in some other more old-fashioned way:


(The code is quite tricky, more explanations below)
class _Const(object):
@apply
def FOO():
def fset(self, value):
raise SyntaxError
def fget(self):
return 0xBAADFACE
return property(**locals())

CONST = _Const()
print CONST.FOO
##3131964110
CONST.FOO = 0
##Traceback (most recent call last):
## ...
## CONST.FOO = 0
##SyntaxError: None

Note that the @apply decorator seems to deprecated.


1.
To define the identifier FOO, firs define two functions (fset, fget - the names
are at my choice).
2.

Then use the built-in property function to construct an object that can be
"set" or "get".
3.
Note hat the property function's first two parameters are
named fset and fget.
4.
Use the fact that we chose these very names for our own getter & setter and
create a keyword-dictionary using the ** (double asterisk) applied to all the
local definitions of that scope to pass parameters to the property function

In Python instead of language enforcing something, people use naming


conventions e.g __method for private methods and using _method for protected
methods.
So in same manner you can simply declare the constant as all caps e.g.
MY_CONSTANT = "one"

If you want that this constant never changes, you can hook into attribute access
and do tricks, but a simpler approach is to declare a function
def MY_CONSTANT():
return "one"

Only problem is everywhere you will have to do MY_CONSTANT(), but


again MY_CONSTANT = "one"is the correct way in python(usually).
You can also use namedtuple to create constants:
>>> from collections import namedtuple
>>> Constants = namedtuple('Constants', ['pi', 'e'])
>>> constants = Constants(3.14, 2.718)
>>> constants.pi
3.14
>>> constants.pi = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

You might also like