开发者

Is this a legal use of global variables in Python?

I've written a small script in Python for simple text manipulation, consist开发者_Go百科ing of a bunch of functions. Some of these functions contain magic numbers or string constants. Is it okay to store them in global variables? I do not intent to modify them, they are more like constants.


Yes, it's legimitate use. You will encounter that in many good Python codes. Just note that the convention is to write the names of such "constants" in UPPER_CASE.


This is the preferred way of dealing with constants. At the top of the file you can easily modify them.

You could also move them to a seperate file and use the absolute or relative import.

from mypackage import constants as c # absolute -- any Python
from . import constants as c # relative -- Python 2.6+
from .constants import * # Resist any temptation to do this!


Yes it is okay to store constants as global variables. For example Django (a Python web framework) does this with a lot of settings in a settings.py file, which contains globals such as

LOGGER = ...
STATIC_DIR = ...

etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜