判断Python中是否定义了变量

发布于 2024-08-08 11:40:13 字数 310 浏览 10 评论 0原文

如何知道运行时代码中的特定位置是否已设置变量?这并不总是显而易见的,因为 (1) 可以有条件地设置变量,并且 (2) 可以有条件地删除变量。我正在寻找类似 Perl 中的 define() 或 PHP 中的 isset() 或 Ruby 中的 define? 的内容。

if condition:
    a = 42

# is "a" defined here?

if other_condition:
    del a

# is "a" defined here?

How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I'm looking for something like defined() in Perl or isset() in PHP or defined? in Ruby.

if condition:
    a = 42

# is "a" defined here?

if other_condition:
    del a

# is "a" defined here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

情栀口红 2024-08-15 11:40:13
try:
    thevariable
except NameError:
    print("well, it WASN'T defined after all!")
else:
    print("sure, it was defined.")
try:
    thevariable
except NameError:
    print("well, it WASN'T defined after all!")
else:
    print("sure, it was defined.")
一世旳自豪 2024-08-15 11:40:13

vars() 中的 'a' 或 globals() 中的 'a'

如果你想学究气,你也可以检查内置函数
vars(__builtins__) 中的“a”

'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)

沙沙粒小 2024-08-15 11:40:13

我认为最好避免这种情况。写起来更干净、更清晰:

a = None
if condition:
    a = 42

I think it's better to avoid the situation. It's cleaner and clearer to write:

a = None
if condition:
    a = 42
筑梦 2024-08-15 11:40:13
try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope
try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope
∝单色的世界 2024-08-15 11:40:13

对于这种特殊情况,最好使用 a = None 而不是 del a。这将减少分配给对象a(如果有)的引用计数,并且在未定义a时不会失败。请注意,del 语句不会直接调用对象的析构函数,而是将其与变量解除绑定。当引用计数变为零时,调用对象的析构函数。

For this particular case it's better to do a = None instead of del a. This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.

热风软妹 2024-08-15 11:40:13

可能需要这样做的一种可能情况是:

如果您使用 finally 块来关闭连接,但在 try 块中,程序将通过 sys.exit() 退出 在定义连接之前。在这种情况下,将调用finally 块,并且连接关闭语句将失败,因为没有创建连接。

One possible situation where this might be needed:

If you are using finally block to close connections but in the try block, the program exits with sys.exit() before the connection is defined. In this case, the finally block will be called and the connection closing statement will fail since no connection was created.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文