判断Python中是否定义了变量
如何知道运行时代码中的特定位置是否已设置变量?这并不总是显而易见的,因为 (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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
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__)
我认为最好避免这种情况。写起来更干净、更清晰:
I think it's better to avoid the situation. It's cleaner and clearer to write:
对于这种特殊情况,最好使用
a = None
而不是del a
。这将减少分配给对象a
(如果有)的引用计数,并且在未定义a
时不会失败。请注意,del 语句不会直接调用对象的析构函数,而是将其与变量解除绑定。当引用计数变为零时,调用对象的析构函数。For this particular case it's better to do
a = None
instead ofdel a
. This will decrement reference count to objecta
was (if any) assigned to and won't fail whena
is not defined. Note, thatdel
statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.可能需要这样做的一种可能情况是:
如果您使用
finally
块来关闭连接,但在try
块中,程序将通过sys.exit() 退出
在定义连接之前。在这种情况下,将调用finally
块,并且连接关闭语句将失败,因为没有创建连接。One possible situation where this might be needed:
If you are using
finally
block to close connections but in thetry
block, the program exits withsys.exit()
before the connection is defined. In this case, thefinally
block will be called and the connection closing statement will fail since no connection was created.