IT박스

"설정"모듈을 사용하여 상수를 만드시겠습니까?

itboxs 2020. 10. 21. 07:49
반응형

"설정"모듈을 사용하여 상수를 만드시겠습니까?


저는 비교적 Python에 익숙하지 않습니다. 다양한 응용 프로그램 별 상수가 저장 될 "설정"모듈을 만들려고합니다.

다음은 내 코드를 설정하는 방법입니다.

settings.py

CONSTANT = 'value'

script.py

import settings

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

다음과 같은 Python 오류가 발생합니다.

global name 'CONSTANT' is not defined.

Django의 소스 코드에서 settings.py파일에 저와 같은 이름의 상수 가 있음을 알았습니다 . 스크립트로 가져오고 응용 프로그램을 통해 참조 할 수있는 방법에 대해 혼란 스럽습니다.

편집하다

모든 답변에 감사드립니다! 다음을 시도했습니다.

import settings

print settings.CONSTANT

같은 오류가 발생합니다

ImportError: cannot import name CONSTANT


가장 쉬운 방법은 설정을 모듈로 만드는 것입니다.

(settings.py)

CONSTANT1 = "value1"
CONSTANT2 = "value2"

(consumer.py)

import settings

print settings.CONSTANT1
print settings.CONSTANT2

파이썬 모듈을 가져올 때 모듈 이름을 가져 오는 변수 앞에 접두사를 붙여야합니다. 주어진 파일에서 사용할 값을 정확히 알고 있고 실행 중에 변경되는 것에 대해 걱정하지 않는다면 다음을 수행 할 수 있습니다.

from settings import CONSTANT1, CONSTANT2

print CONSTANT1
print CONSTANT2

그러나 나는 그 마지막 것에 휩쓸 리지 않을 것입니다. 코드를 읽는 사람들이 값의 출처를 파악하기 어렵게 만듭니다. 다른 클라이언트 모듈이 값을 변경하면 해당 값이 업데이트되지 않도록합니다. 이를 수행하는 마지막 방법은

import settings as s

print s.CONSTANT1
print s.CONSTANT2

이렇게하면 입력을 절약하고 업데이트를 전파하며 독자 만 s설정 모듈에서 가져온 내용 임을 기억하면 됩니다.


1 단계 : 더 쉽게 액세스 할 수 있도록 동일한 디렉토리에 settings.py 파일을 새로 만듭니다.

#database configuration settings

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

#application predefined constants

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

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

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 tip you can import all the code on the settings file by 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.


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


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.


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

import settings

def func():
    var = settings.CONSTANT

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

from settings import *

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


I'm new in python but if we define an constant like a function on setings.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..


Try this:

In 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.


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

참고URL : https://stackoverflow.com/questions/3824455/create-constants-using-a-settings-module

반응형