简体   繁体   English

如何检查全局变量是否存在,如果不存在则将其定义为全局变量?

[英]How to check if a global variable exists and if not then define it as global?

I wish to do :我希望这样做:

if var not in globals():
     global var
     var = -1

or要么

try : var
except NameError :
    global var
    var = -1

The problem is :问题是 :

global var
^
SyntaxError: name 'var' is used prior to global declaration

So what can be done to achieve similar effect ?那么如何做才能达到类似的效果呢?


EDIT :编辑 :

This is not at module level, but rather in a function.这不是在模块级别,而是在函数中。 The variable is supposed to store a position value that the function uses and updates in it but needs to persist between calls.该变量应该存储函数使用和更新的位置值,但需要在调用之间保持不变。

I have been made aware that the above code is bad practise, and I agree, and request those agreeing to suggest alternative "good practise" methods, if possible.我已经意识到上述代码是不好的做法,我同意,并要求那些同意建议替代“良好做法”方法的人,如果可能的话。


EDIT 2 :编辑 2:

This question is required to help me fix my previous question .需要这个问题来帮助我解决我之前的问题 There, the obj_cnt is getting reset at every call, bugging up the function that accesses objects from a pickled file by an "index" (an abstraction), as I try to avoid unnecessary seeking and reading by querying indexes in sorted order.在那里, obj_cnt在每次调用时都被重置,通过“索引”(抽象)来obj_cnt从腌制文件访问对象的函数,因为我试图通过按排序顺序查询索引来避免不必要的查找和读取。

The above should clear up the "Why?"以上应该澄清“为什么?” part.部分。


EDIT 3:编辑 3:

I did not end up needing to do this convoluted stuff.我最终不需要做这些令人费解的事情。 I solved the above question by using classes.我通过使用类解决了上述问题。

Nevertheless, thanks to everyone who helped me here.尽管如此,还是要感谢所有在这里帮助过我的人。

It is considered bad practice to alter the global variables (see Why are global variables evil? ) , but for the sake of knowledge, you can do:改变全局变量被认为是不好的做法(请参阅为什么全局变量是邪恶的? ,但为了知识起见,您可以这样做:

if 'var' not in globals():
     globals()['var'] = var
     var = -1

for what you're trying to do.对于你正在尝试做的事情。

The global keyword doesn't unilaterally declare a variable name as a module level variable. global关键字不会单方面将变量名声明为模块级变量。 It is used within a function to declare that assignments to a variable should be in the module namespace instead of the function instance namespace.它在函数中用于声明对变量的赋值应该在模块命名空间中,而不是在函数实例命名空间中。 The global keyword makes no sense at module level because the module namespace is already the place variable assignments go. global关键字在模块级别没有意义,因为模块命名空间已经是变量赋值的地方。

So, just leave the global out.所以,把全局放在外面。

try:
    var
except NameError:
    var = 1
print(var)

In a function you need the global, but it needs to be before first use.在一个函数中你需要全局,但它需要在第一次使用之前。

def foo():
    global var
    try:
        var += 1
    except NameError:
        print("making var")
        var = 1
    return var

print(foo())
print(foo())

Outputs输出

making var
1
2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM