最佳实践 – Python 中的全局变量

huangapple go评论81阅读模式
英文:

best practice for global variable in python

问题

You can achieve this by using a module-level variable in the "00.py" file and importing it into other files. Here's a brief explanation:

00.py

import adal

v_Token = None  # Initialize v_Token as None

def f_token():
    global v_Token
    if v_Token is None:  # Check if v_Token is None
        auth_context = adal.AuthenticationContext("https://login.microsoftonline.com/common")
        token_response = auth_context.acquire_token_with_username_password("https://xxx.xxx.dynamics.com/", username, password, client_id)
        v_Token = token_response['accessToken']
    return v_Token

This way, you'll only execute f_token once, and the value of v_Token will be reused across files 01, 02, and 03.

英文:

I have the following code across different files. I want to understand what is the best practice to define the global variable so that I don't have to run the function again to get the variable value. File structure as below:

00.py

def f_token():
    global v_Token, v_session
    auth_context = adal.AuthenticationContext("https://login.microsoftonline.com/common")
    token_response = auth_context.acquire_token_with_username_password("https://xxx.xxx.dynamics.com/", username, password, client_id)
    v_Token= token_response['accessToken']
    return v_Token

01.py

from 00 import*
A_Token = f_token()
def f_meta():
    code here

02.py

from 00 import*
A_Token = f_token()
def f_anotherfunction():
    code here

03.py

from 00 import*
A_Token = f_token()
def f_function():
    code here

I only want to execute f_token once and reuse the value of v_Token across file 01,02, and 03. These 3 functions are not dependant on each other. They are being executed separately. What would be the best practice for this problem?

答案1

得分: 1

假设这段代码可能是多线程的,您可以使用锁来控制对全局变量的访问。全局资源最初为None,找到None的第一个调用者会获取令牌。将来的调用者会注意到它不再是None,然后跳过额外的工作。

import threading

v_lock = threading.Lock()
v_Token = v_session = None

def f_token():
    global v_Token, v_session
    # 当令牌已经获取时进行短路操作
    if not v_Token:
        # 锁定,确保没有竞争条件,获取令牌
        with v_lock:
            if v_Token is None:    
                auth_context = adal.AuthenticationContext("https://login.microsoftonline.com/common")
                token_response = auth_context.acquire_token_with_username_password("https://xxx.xxx.dynamics.com/", username, password, client_id)
                v_Token = token_response['accessToken']
    return v_Token

您可能不希望在其他模块中使用模块级别的A_Token = f_token()调用。通常,简单的导入不应该执行像网络身份验证这样重要的操作。这会使测试变得困难,并且代码通常不够可重用。每次需要令牌时,只需调用f_token()

英文:

Assuming this code could be multithreaded, you can control access to the global variable with a lock. The global resource starts out None and the first caller who finds that None acquires the token. Future callers notice it is no longer None and skip the extra work.

import threading

v_lock = threading.Lock()
v_Token = v_session = None

def f_token():
    global v_Token, v_session
    # short circuit when token already acquired 
    if not v_Token:
        # lock, verify no race condition, get token
        with v_lock.lock():
            if v_Token is None:    
                auth_context = adal.AuthenticationContext("https://login.microsoftonline.com/common")
                token_response = auth_context.acquire_token_with_username_password("https://xxx.xxx.dynamics.com/", username, password, client_id)
                v_Token = token_response['accessToken']
    return v_Token

You probably don't want those module level A_Token = f_token() calls in other modules. Simple import generally shouldn't do something as dramatic as network authentication. It makes things hard to test and code is generally less reusable. Just call f_token() every time you need the token.

答案2

得分: 0

将该值保存为模块的顶级(即全局)变量。

module_A.py

A = something(...)

然后其他模块可以导入该变量:

module_B.py

from module_A import A

module_C.py

from module_A import A

module_A.py 中的 something() 函数仅在首次导入时执行。

英文:

Save the value as a top-level (i.e. global) variable in a module.

module_A.py
-----------
A = something(...)

Then other modules can import that variable:

module_B.py
-----------
from module_A import A


module_C.py
-----------
from module_A import A

The something() function inside module_A.py is only executed the first time it is imported.

huangapple
  • 本文由 发表于 2023年5月10日 11:51:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76214767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定