First import the file from the current program, then you can import the variable or access the variable in Python. There are three approaches to importing variables from another file. from <file> import * and then use variables directly.
To use global variables between files in Python, we can use the global keyword to define a global variable in a module file. Then we can import the module in another module and reference the global variable directly. We import the settings and subfile modules in main.py . Then we call settings.
The syntax we're using to export and import variables is called JavaScript modules. In order to be able to import a variable from a different file, it has to be exported using a named or a default export. The example above uses a named export and a named import.
from file1 import *
will import all objects and methods in file1
Import file1
inside file2
:
To import all variables from file1 without flooding file2's namespace, use:
import file1
#now use file1.x1, file2.x2, ... to access those variables
To import all variables from file1 to file2's namespace( not recommended):
from file1 import *
#now use x1, x2..
From the docs:
While it is valid to use
from module import *
at module level it is usually a bad idea. For one, this loses an important property Python otherwise has — you can know where each toplevel name is defined by a simple “search” function in your favourite editor. You also open yourself to trouble in the future, if some module grows additional functions or classes.
Best to import x1 and x2 explicitly:
from file1 import x1, x2
This allows you to avoid unnecessary namespace conflicts with variables and functions from file1
while working in file2
.
But if you really want, you can import all the variables:
from file1 import *
Actually this is not really the same to import a variable with:
from file1 import x1
print(x1)
and
import file1
print(file1.x1)
Altough at import time x1 and file1.x1 have the same value, they are not the same variables. For instance, call a function in file1 that modifies x1 and then try to print the variable from the main file: you will not see the modified value.
script1.py
title="Hello world"
script2.py is where we using script1 variable
Method 1:
import script1
print(script1.title)
Method 2:
from script1 import title
print(title)
Marc response is correct. Actually, you can print the memory address for the variables print(hex(id(libvar))
and you can see the addresses are different.
# mylib.py
libvar = None
def lib_method():
global libvar
print(hex(id(libvar)))
# myapp.py
from mylib import libvar, lib_method
import mylib
lib_method()
print(hex(id(libvar)))
print(hex(id(mylib.libvar)))
first.py:
a=5
second.py:
import first
print(first.a)
The result will be 5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With