gpt4 book ai didi

Python:在 globals() 中检查变量是否存在使其在本地上下文中不可见

转载 作者:行者123 更新时间:2023-11-28 22:47:28 25 4
gpt4 key购买 nike

使用 Ubuntu 14.04 提供的 Python 2.7.6。

我有一些函数引用由调用者定义的变量。我想要一种方法来查找调用者是否设置了变量(如果没有,我会在本地设置默认值),所以我找到了 this answer在 StackOverflow 上。

我遇到的问题是,检查变量是否存在会使它对以下代码不可见/不存在。

为了方便任何调查此问题的人,下面的代码块应该能够直接剪切粘贴到您系统上的文件中以进行测试。

#!/usr/bin/env python

# Tested on Python 2.7.6 from Ubuntu 14.04.

def calledfunction():

print globals()
print
print locals()
print

# Try commenting the next five lines out. While they're here, the variable
# becomes invisible to the print statement below.
if not 'globalvar' in globals():
globalvar = "created within the function"
print "assigning variable locally"
else:
print "variable assigned globally"
# global globalvar
# If you uncomment the above line, the variable is visible, but Python
# prints a syntax warning.

print
print globals()
print
print locals()
print

print "the variable 'globalvar' is:", globalvar
print

# -----------------

print "calling function before the variable is defined"
print
calledfunction()

globalvar = "created outside the function"

print "calling function after the variable is defined"
print
calledfunction()

我的期望是 globals() 测试中的“变量”不应导致变量从其后的打印语句的可见性中消失。我的期望不正确吗? (Python 似乎认为我不是。)

最佳答案

请注意,当您开始像这样动态检查 globals 时,人们会开始怀疑……话虽如此,只要您只“读取”来自全局变量。

def calledfunction():
default_local = 'some default'
var = globalvar if 'globalvar' in globals() else default_local
print var

# -----------------

print "calling function before the variable is defined"
print
calledfunction()

globalvar = "created outside the function"

print "calling function after the variable is defined"
print
calledfunction()

请注意,在函数中,变量名要么是全局的,要么是局部的(python3.x 将 nonlocal 添加到这组变量中)。但是,变量名不能全局或局部变量名,具体取决于调用函数的方式。

更好的方法是只使用关键字参数:

def calledfunction(var="Created within the function"):
print var

calledfunction() # Created within the function
calledfunction(var="Created by the caller") # Created by the caller

当您想以这种方式创建新的可变对象时,会遇到一些问题,但它们是 well known and documented with work-arounds .

关于Python:在 globals() 中检查变量是否存在使其在本地上下文中不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26222720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com