Python 使用“设置”模块创建常量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3824455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:55:24  来源:igfitidea点击:

Create constants using a "settings" module?

python

提问by Lark

I am relatively new to Python. I am looking to create a "settings" module where various application-specific constants will be stored.

我对 Python 比较陌生。我希望创建一个“设置”模块,其中将存储各种特定于应用程序的常量。

Here is how I am wanting to set up my code:

这是我想要设置我的代码的方式:

settings.py

设置.py

CONSTANT = 'value'

script.py

脚本文件

import settings

def func():
    var = CONSTANT
    # do some more coding
    return var

I am getting a Python error stating:

我收到一个 Python 错误,说明:

global name 'CONSTANT' is not defined.

global name 'CONSTANT' is not defined.

I have noticed on Django's source code their settings.pyfile has constants named just like I do. I am confused on how they can be imported to a script and referenced through the application.

我注意到在 Django 的源代码中,他们的settings.py文件和我一样命名了常量。我对如何将它们导入脚本并通过应用程序引用感到困惑。

EDIT

编辑

Thank you for all your answers! I tried the following:

感谢您的所有回答!我尝试了以下方法:

import settings

print settings.CONSTANT

I get the same error

我犯了同样的错误

ImportError: cannot import name CONSTANT

ImportError: cannot import name CONSTANT

采纳答案by aaronasterling

The easiest way to do this is to just have settings be a module.

最简单的方法是让设置成为一个模块。

(settings.py)

(设置.py)

CONSTANT1 = "value1"
CONSTANT2 = "value2"

(consumer.py)

(消费者.py)

import settings

print settings.CONSTANT1
print settings.CONSTANT2

When you import a python module, you have to prefix the the variables that you pull from it with the module name. If you know exactly what values you want to use from it in a given file andyou are not worried about them changing during execution, then you can do

导入 python 模块时,必须在从中提取的变量前面加上模块名称。如果您确切地知道要在给定文件中使用它的哪些值,并且您不担心它们在执行过程中会发生变化,那么您可以这样做

from settings import CONSTANT1, CONSTANT2

print CONSTANT1
print CONSTANT2

but I wouldn't get carried away with that last one. It makes it difficult for people reading your code to tell where values are coming from. and precludes those values being updated if another client module changes them. One final way to do it is

但我不会对最后一个得意忘形。阅读你的代码的人很难判断值的来源。如果另一个客户端模块更改这些值,则阻止这些值被更新。最后一种方法是

import settings as s

print s.CONSTANT1
print s.CONSTANT2

This saves you typing, will propagate updates and only requires readers to remember that anything after sis from the settings module.

这可以节省您的输入,将传播更新,并且只需要读者记住之后的任何内容s都来自设置模块。

回答by Ned Batchelder

Leave your settings.py exactly as it is, then you can use it just as Django does:

保持你的 settings.py 原样,然后你可以像 Django 一样使用它:

import settings

def func():
    var = settings.CONSTANT

回答by aaronasterling

When you import settings, a moduleobject called settingsis placed in the global namespace - and this object carries has that was in settings.pyas attributes. I.e. outside of settings.py, you refer to CONSTANTas settings.CONSTANT.

当你import settings,一个module名为的对象settings被放置在全局命名空间中 - 这个对象携带有settings.py作为属性。即外面的settings.py,你指的CONSTANTsettings.CONSTANT

回答by ewall

...Or, if you reallywant all the constants from settings.py to be imported into the global namespace, you can run

...或者,如果您真的希望将 settings.py 中的所有常量导入全局命名空间,您可以运行

from settings import *

...but otherwise using settings.CONSTANT, as everyone else has mentioned here, is quite right.

...但除此之外settings.CONSTANT,正如其他人在这里提到的那样,使用 是完全正确的。

回答by kcunning

Try this:

尝试这个:

In settings.py:

在 settings.py 中:

CONSTANT = 5

In your main file:

在您的主文件中:

from settings import CONSTANT

class A:
    b = CONSTANT

    def printb(self):
         print self.b

I think your above error is coming from the settings file being imported too late. Make sure it's at the top of the file.

我认为您的上述错误来自导入太晚的设置文件。确保它位于文件的顶部。

回答by martineau

See the answer I posted to Can I prevent modifying an object in Python?which does what you want (as well as force the use of UPPERCASE identifiers). It might actually be a better answer for this question than it was for the the other.

请参阅我发布的答案是否可以防止在 Python 中修改对象?它可以满足您的需求(并强制使用大写标识符)。对于这个问题,它实际上可能比另一个问题的答案更好。

回答by IVI

I'm new in python but if we define an constant like a function on setings.py

我是 python 新手,但如果我们在 settings.py 上定义一个常量,比如函数

def CONST1():
    return "some value"

main.py

主文件

import setings

print setings.CONST1() ##take an constant value

here I see only one, value cant be changed but its work like a function..

在这里我只看到一个,值不能改变,但它的工作就像一个函数..

回答by Fady Faried

step 1: create a new file settings.py on the same directory for easier access.

第 1 步:在同一目录下创建一个新文件 settings.py 以便于访问。

#database configuration settings

database = dict(
    DATABASE = "mysql",
    USER     = "Lark",
    PASS     = ""
)

#application predefined constants

app = dict(
    VERSION   = 1.0,
    GITHUB    = "{url}"
)

step 2: importing settings module into your application file.

第 2 步:将设置模块导入您的应用程序文件。

import settings as s            # s is aliasing settings & settings is the actual file you do not have to add .py 

print(s.database['DATABASE'])   # should output mysql

print(s.app['VERSION'])         # should output 1.0

if you do not like to use alias like s you can use a different syntax

如果你不喜欢像 s 这样的别名,你可以使用不同的语法

from settings import database, app

print(database['DATABASE'])   # should output mysql

print(app['VERSION'])         # should output 1.0

notice on the second import method you can use the dict names directly

注意第二种导入方法,您可以直接使用字典名称

A small tipyou can import allthe code on the settings fileby using * in case you have a large file and you will be using most of the settings on it on your application

一个小提示,您可以使用 *导入设置文件中所有代码,以防您有一个大文件,并且您将在应用程序中使用其中的大部分设置

from settings import *      # * represent all the code on the file, it will work like step 2


print(database['USER'])       # should output lark

print(app['VERSION'])         # should output 1.0

i hope that helps.

我希望有帮助。

回答by Gregor

Also worth checking out is the simple-settingsproject which allows you to feed the settings into your script at runtim, which allows for environment-specific settings (think dev, test, prod,...)

同样值得一试的是simple-settings项目,它允许您在运行时将设置输入到脚本中,从而允许特定于环境的设置(想想 dev、test、prod...)

回答by charls

This way is more efficient since it loads/evaluates your settings variables only once. It works well for all my Python projects.

这种方式更有效,因为它只加载/评估您的设置变量一次。它适用于我所有的 Python 项目。

pip install python-settings

Docs here: https://github.com/charlsagente/python-settings

文档在这里:https: //github.com/charlsagente/python-settings

You need a settings.py file with all your defined constants like:

您需要一个包含所有定义常量的 settings.py 文件,例如:

# settings.py

DATABASE_HOST = '10.0.0.1'

Then you need to either set an env variable (export SETTINGS_MODULE=settings) or manually calling the configure method:

然后您需要设置一个环境变量(导出 SETTINGS_MODULE=settings)或手动调用配置方法:

# something_else.py

from python_settings import settings
from . import settings as my_local_settings

settings.configure(my_local_settings) # configure() receives a python module

The utility also supports Lazy initialization for heavy to load objects, so when you run your python project it loads faster since it only evaluates the settings variable when its needed

该实用程序还支持重载对象的延迟初始化,因此当您运行 python 项目时,它加载速度更快,因为它仅在需要时评估设置变量

# settings.py

from python_settings import LazySetting
from my_awesome_library import HeavyInitializationClass # Heavy to initialize object

LAZY_INITIALIZATION = LazySetting(HeavyInitializationClass, "127.0.0.1:4222") 
# LazySetting(Class, *args, **kwargs)

Just configure once and now call your variables where is needed:

只需配置一次,然后在需要的地方调用变量:

# my_awesome_file.py

from python_settings import settings 

print(settings.DATABASE_HOST) # Will print '10.0.0.1'