Importing file2 in file1.py makes the global (i.e., module level) names bound in file2 available to following code in file1 -- the only such name is SomeClass. It does not do the reverse: names defined in file1 are not made available to code in file2 when file1 imports file2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the way you're doing it.
Apparently you want to make global names defined in file1 available to code in file2 and vice versa. This is known as a "cyclical dependency" and is generally not recommended.
It is often more useful to discuss ways to avoid cyclic dependencies.
For example, you could put global names that need to be available to both modules in a third module (e.g. file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3 in both file1 and file2, and then use file3.foo etc, that is, qualified names, for the purpose of accessing or setting those global names from either or both of the other modules, not barenames).
Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly why you think you need a cyclical dependency. Note that it is usually not the right answer.
Answer from Alex Martelli on Stack OverflowImporting file2 in file1.py makes the global (i.e., module level) names bound in file2 available to following code in file1 -- the only such name is SomeClass. It does not do the reverse: names defined in file1 are not made available to code in file2 when file1 imports file2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the way you're doing it.
Apparently you want to make global names defined in file1 available to code in file2 and vice versa. This is known as a "cyclical dependency" and is generally not recommended.
It is often more useful to discuss ways to avoid cyclic dependencies.
For example, you could put global names that need to be available to both modules in a third module (e.g. file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3 in both file1 and file2, and then use file3.foo etc, that is, qualified names, for the purpose of accessing or setting those global names from either or both of the other modules, not barenames).
Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly why you think you need a cyclical dependency. Note that it is usually not the right answer.
When you write
from file2 import *
it actually copies the names defined in file2 into the namespace of file1. So if you reassign those names in file1, by writing
foo = "bar"
for example, it will only make that change in file1, not file2. Note that if you were to change an attribute of foo, say by doing
foo.blah = "bar"
then that change would be reflected in file2, because you are modifying the existing object referred to by the name foo, not replacing it with a new object.
You can get the effect you want by doing this in file1.py:
import file2
file2.foo = "bar"
test = SomeClass()
(note that you should delete from foo import *) although I would suggest thinking carefully about whether you really need to do this. It's not very common that changing one module's variables from within another module is really justified.
The problem is you defined myList from main.py, but subfile.py needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py. This file is responsible for defining globals and initializing them:
# settings.py
def init():
global myList
myList = []
Next, your subfile can import globals:
# subfile.py
import settings
def stuff():
settings.myList.append('hey')
Note that subfile does not call init()— that task belongs to main.py:
# main.py
import settings
import subfile
settings.init() # Call only once
subfile.stuff() # Do stuff with global var
print settings.myList[0] # Check the result
This way, you achieve your objective while avoid initializing global variables more than once.
See Python's document on sharing global variables across modules:
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).
config.py:
x = 0 # Default value of the 'x' configuration settingImport the config module in all modules of your application; the module then becomes available as a global name.
main.py:
import config print (config.x)
In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.
Global variables shared across modules
Global Variable file
passing global variables to another file in Python? - Stack Overflow
How to import variable from another file if another file write the code inside def main():
Videos
So currently I am working on a project where I decided to make a file called global_variables.py. This file consists of python dictionaries where I would like to store data throughout the process of the program.
The program consists of 3 classes that are called one by one by a main.py file. Each class import the global variables files and makes changes to the file. Now I realized that this is not the way to go because each class makes a different iteration of the global variable files.
How can I approach this so the global variables gets "saved" ready for the next class to import it and use it? Should I just use a JSON file?
You don't need to pass them. If you've done import file1 at the top of main.py, you can just refer to file1.a etc directly.
However, having this many global variables smells very bad. You probably should refactor using a class.
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:
config.py:
x = 0 # Default value of the 'x' configuration setting
mod.py:
import config
config.x = 1
main.py:
import config
import mod
print config.x
For example, I want to import all variables from file work.py to use in my current file. The code in work.py is written inside def main():
If I use-> from work import *
It seems to import only variables outside function “main”. I cannot access to the variables created inside function “main”. How to access to variables inside function main?
config/global_var.py has 10-20 variables which are used by ***main_methods/***main.py
Currently i see two options
-
from config/global_var import *
-
not advisable generally
-
even if variable x is used in main, however user won't know where this variable is defined by IDE
-
from config/global_var import x,y,z....
-
explicitly define all variables to be imported
-
takes too many lines if vars more than 20 30 etc
How do you import global variables in a project in a clean way while preserving reference to original file where it was defined?
As per your question I understand you are the beginner to the python.
While importing the modules you have use just module name and don't need to include the extension or suffix(py) and in your code you miss the starting single quote .
Here is your modified code: it is modules.py
dns_server_ip = ''
def SetVnetGlobalParameters():
global dns_server_ip
dns_server_ip = '192.168.3.120′
Here is your abc.py
import modules
modules.SetVnetGlobalParameters()
print modules.dns_server_ip
Here through the global keyword we are telling the python interpreter to change or point out the global variable instead of local variable and always the variable would be either global or local If the variable is both (local and global) you will get python UnboundLocalError exception and if you did not put that global keyword
global dns_server_ip
The dns_server_ip will be created as a new local variable . The keyword global intended to with in the functions only
you can check global keyword,python modules
In modules.py
dns_server_ip = None
def SetVnetGlobalParameters():
global dns_server_ip
dns_server_ip = '192.168.3.120'
In abc.py
import modules
modules.SetVnetGlobalParameters()
print(modules.dns_server_ip)
All that from config import ADDRESS, change_address does is take ADDRESS and change_address from your config module's namespace and dumps it into your current module's namespace. Now, if you reassign the value of ADDRESS in config's namespace, it won't be seen by the current module - that's how namespaces work. It is like doing the following:
>>> some_namespace = {'a':1}
>>> globals().update(some_namespace)
>>> a
1
>>> some_namespace
{'a': 1}
>>> some_namespace['a'] = 99
>>> a
1
>>> some_namespace
{'a': 99}
The simplest solution? Don't clobber name-spaces:
import config
config.change_address("192.168.10.100")
print("new address " + config.ADDRESS)
I would recommend that you try not to change the global state in a module. Instead, I would re-write the code such that ADDRESS in config.py doesn't change. If the configuration for your application can change from invocation to invocation I would change config to be something like:
ADDRESS = '0.0.0.0'
def get_default_config():
return {'address': ADDRESS, 'some_other_config_value': 'foo'}
Then in main I would do:
app_config = config.get_default_config()
app_config = "192.168.10.100"
print("new address " + app_config['address']
As a general rule it isn't a good idea to change the value of variables/constants in other modules.
NOTE: You could also create a config class as well, so that you could access configuration values like config.address.
I recommend that you read the stackexchange post Why is Global State so Evil?