How to set global constant variables in python

I am creating a solution with various classes and functions, all of which need access to some global harmonization in order to be able to work accordingly. Since python does not have const , what would you consider best practice for setting some kind of global negotiation.

 global const g = 9.8 

So I'm looking for something like

Edit: How about:

 class Const(): @staticmethod def gravity(): return 9.8 print 'gravity: ', Const.gravity() 

?

+6
source share
2 answers

You cannot define constants in Python. If you find something like this, you just embarrass everyone.

To do such things, usually you should only have a module - globals.py , for example, which you import wherever you need it

+9
source

The general agreement is to define variables with capital and underscores and not change them. How,

 GRAVITY = 9.8 

However, it is possible to create constants in Python using namedtuple

 import collections Const = collections.namedtuple('Const', 'gravity pi') const = Const(9.8, 3.14) print(const.gravity) # => 9.8 # try to change, it gives error const.gravity = 9.0 # => AttributeError: can't set attribute 

For namedtuple refer to the docs here

+6
source

Source: https://habr.com/ru/post/951689/


All Articles