The existing answer from @Polosson is correct, however Im a bit biased against globals since I have had to debug other peoples code with many globals - it can become difficult, if the code becomes complex and there are more then 2-3 of them used across multiple functions. It's a pain to keep track of them, forgetting to add a global
keyword, it can fail in a non-obvious way.
Store in a global dictionary
Heres an alternative, which I prefer in some cases.
# store all runtime variables here.
runtime = {}
runtime["hmd"] = None
def poll():
# declare hmd as global so that the function has (write) access to the global var.
if runtime["hmd"] is None:
runtime["hmd"] = ctypes.WinDLL("C:\\Program Files\\Blender Foundation\\Blender\\2.68\\scripts\\addons\\game_engine_rift\\openhmd.dll")
You can store the runtime state in a dictionary, and it has some advantages that you can easily print(runtime)
, runtime.clear()
... etc. and pass it to other modules if you end up splitting your code across files.
Because the dictionary its self is never re-assigned, you don't have to define it as global.
Store in the function
Another trick, is you can store the variable in the function (and avoid using globals)
Note that this is not the functions local namespace, which is why it has to be accessed as an attribute of the function, even when inside the function body.
def poll():
# declare hmd as global so that the function has (write) access to the global var.
if poll.hmd is None:
poll.hmd = ctypes.WinDLL("C:\\Program Files\\Blender Foundation\\Blender\\2.68\\scripts\\addons\\game_engine_rift\\openhmd.dll")
poll.hmd = None
Sometimes I use this for global variables that only the function ever accesses.
For more info on function attributes see:
Q: Python function attributes - uses and abuses