Since variables names are declared local if there is an assignment to them within a function, and I want to access the module variables from within a function, can I import the module name within the module and then use that to access the module variables ?
Example (file name : server.py):
import server
bar = 5
def foo():
server.bar = 10
Instead of using the
globalstatement, as suggested in all of the other answers, don’t use module level variables, but a class as a container or else another module just for the globals:or
This way you don’t need to put
globalstatements everywhere, you can re-use those names, and it’s clear whichbaryou’re referring to.Edit: Also, it is possible to import a module inside itself, but you can’t change variables in the main module that way. So this would work:
But this wouldn’t:
If you’re only using the globals as constants, you wouldn’t need the
globalstatement anyway. You also need to make sure to wrap code you only want to execute in the main module in anifstatement as above, or you’ll recurse.