Python Const and pythonconst
Python const implementation
Python const implementation
The python language does not provide const, but const is often used in actual development. Because the language itself does not have such expenditure, you need some skills to implement this function.
The const class is defined as follows:
import sysclass Const(object): class ConstError(TypeException): pass def __setattr__(self, key, value): if self.__dict__.has_key(key): raise self.ConstError, "Changing const.%s" % key else: self.__dict__[key] = value def __getattr__(self, key): if self.__dict__.has_key(key): return self.key else: return Nonesys.modules[__name__] = Const()
Use sys. modules [Name] You can obtain a module object and obtain the attributes of the module through this object. sys is used here. modules injects a Const object into the system dictionary to implement the function of actually obtaining a const instance when executing import Const, sys. the description of the module in this document is as follows:
sys.modulesThis is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.
Sys. modules [Name] = Const () This statement replaces the const in the list of loaded modules with Const (), that is, a Const instance.
In this way, the constants required for the entire project should be defined in a file, as follows:
from project.utils import constconst.MAIL_PROTO_IMAP = 'imap'const.MAIL_PROTO_GMAIL = 'gmail'const.MAIL_PROTO_HOTMAIL = 'hotmail'const.MAIL_PROTO_EAS = 'eas'const.MAIL_PROTO_EWS = 'ews'
First, we need to explain the differences between import module and import from module in python.
- Import module onlyNameAdded to the local Dictionary of the target file. You do not need to explain the module.
- From module import xxx needs to interpret the module, load it into the memory, and then add the corresponding part to the local Dictionary of the target file
- The code in the python module is executed only once when it is imported for the first time.
From project. utils import const, sys. modules [Name] = Const (). At this time, the const module has been loaded into the memory, and the system dictionary has a Const object. Then you can use the Const instance.
To use a constant value in other files, call
from project.apps.project_consts import constprint const.MAIL_PROTO_IMAP