开发者

asynchronous global variable behavior with intra module globals in python

So I have a global variables module global_var.py that looks like this:

x = 1
y = 2

When I want to access these variables all I can do something like this:

import global_var

# read var
print global_var.x
# change var
global_var.x = 0

What I have noticed is that sometimes if I change a global variable and immediately try to read it then sometimes I get the old value. For example

import global_va开发者_运维问答r

global_var.x = 'new'
if global_var.x == 'new':
    print 'changed'
else:
    print 'not changed'

The above operation appears to be probabilistic via asynchronicity. So what is up with this, is there a way to make this sort of thing deterministic, or should I just not do this?


Ok I found my bug, python still works and is as synchronous as ever, all is well, thanks for everyones time and suggestions.


The behavior you described isn't something that should ever happen if you're just doing the thing you said you're doing. Double check your code, perhaps you don't actually set a new value in certain cases you think you do; or perhaps you read before you write sometimes; or maybe you have threads, and the exact ordering of reads and writes is non-deterministic. If your globals are actually in your __main__ module (that is, the .py file you execute on the command line), then maybe you have two copies of them (one copy created when the .py file is turned into the __main__ module because you ran it on the command line; a second copy created when another module imports it by its name, creating a new module with a duplicate copy of all your code and data). As a very unlikely alternative, perhaps the memory in your computer is failing and causing incorrect, unpredictable behavior.

Setting an attribute always sets it (or at least calls the special method which is responsible for setting it - you might override this special method to not set it for some reason, but then it's your fault. :)

Beyond that, using "global variable modules" like this is a bad idea if you want to create understandable, maintainable, testable(, working) software. This is a kind of "spooky action at a distance". Who knows what other parts of your program you will affect whenever you set one of these variables. Instead of this pattern, pass arguments to each function. Make each function's signature include all of the state that it needs to do its job. If you have a lot of state and don't like long argument signatures, then consider making objects to hold that state and adding methods to those objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜