My question is very simple. I have a piece of code that I want to reuse, but I don't want to copy it every time I use it. Is there any way I can import it and run it in my main file?
For example, in file code1.py:
a=1
I want to run in code2.py:
import code1
b=a+1
print(b)
The output says a is not defined. I don't know where I got it wrong. I am a beginner in Python, so this will help me a lot in the future, thanks.
Ensure that the two files are in the same directory.
If this is the case, you can directly import
from filename import variablename/class/function
in your case:
from code1 import a
This lesson is good to understand imports in python: https://realpython.com/python-import/
You will need to import the variable from the your Python module to use it.
from code1 import a
The import statement will differ slightly if your modules are not at the same level.
The code showed below is based on the fact that files code1.py and code2.py are in the same directory.
Solution 1
In this code I have changed only your import instruction in code2.py:
from code1 import a
b = a + 1
print(b)
Solution 2
In this solution I don't have changed your import instruction in the file code2.py, but I have used the module name (code1) to refer to a variable. In this case it is used the access notation moduleName.variableName.
So the file code2.py becomes:
import code1
b = code1.a + 1
print(b)
This means that in this case code1.py is used as a Python module and not as a script (the difference between script and module could be the topic of an other question).
Python namespace
In Python terminology the moduleName is the namespace defined by the module. By the namespace (that is the name placed after the import instruction) you can access to the objects content inside the module by the syntax namespace.object.
The interpreter creates a global namespace for any module that your program loads with the import statement.
About namespace useful this link of realpython.
Related
Let's say I have a structure like this:
tests----------------
___init__.py
test_functions_a
functions-----------
___init__.py
functions_a
functions_b
I want to test a function from functions_a, but inside functions_a I am importing a function from functions_b.
When I am trying:
from functions.functions_a import function_aa
I am getting an error, because inside functions_a I have a line:
from functions_b import function_bb
and not:
from functions.functions_b import function_bb
How can I solve this?
Any good practises are welcome, as I have no experience in structuring projects.
According to Google Python Style Guide, you should:
Use import statements for packages and modules only, not for
individual classes or functions. Note that there is an explicit
exemption for imports from the typing module.
You should also:
Import each module using the full pathname location of the module.
If you follow those two conventions, you will probably avoid, in the future, situations like the one you just described.
Now, here's how your code will probably look like if you follow those tips:
Module functions.functions_a:
from functions import functions_b as funcs_b
def function_aa():
print("AA")
def function_aa_bb():
function_aa()
funcs_b.function_bb()
Module functions.functions_b:
def function_bb():
print("BB")
And, finally, test_functions_a.py:
from functions import functions_a as funcs_a
if __name__ == "__main__":
funcs_a.function_aa()
funcs_a.function_aa_bb()
Output:
AA
AA
BB
You cannot directly import the function instead you could import File 1 to some other File and then call the function from that particular file you imported .
This question already has an answer here:
Why Python print my output two times when I import the same file in which I am printing?
(1 answer)
Closed 2 years ago.
Here is the code
import random
print("Hello", end="")
print("twice")
and a screenshot of the code
When I execute this code it for some reason is running twice. The problem seems to be from the import random statement, because if I either remove that statement or import some other module it works fine.
What could be the reason for this, should I reinstall Python on my system.
There's nothing wrong with python.
The reason is simple:
Your module is importing itself (because it is also named random) - this has to do with the lookup mechanics of python. python will try to import from your root folder first, before modules from pythonpath are imported.
From the docs:
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
The directory containing the input script (or the current directory
when no file is specified).
PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
The installation-dependent default.
Since your file (module) is called random.py, import random will import this very file.
Now, what does "import" mean?
The statement import something will cause Python to lookup the name something, starting with the current directory.
Therefore, import random will result in an import of this very file, since its name will shadow the build-in random.
Besides, if the name to import is already in the namespace, then the import statement is ignored.
Once the module to import has been located, its code is executed.
As a result, the flow of your script is as follow:
Lookup the random.py name
Add random to the namespace
Execute the code contained in random.py
The random name already exists in the namespace, so the import random statement is ignored
Print the text
Print the text
The reason for this is you've named the script random.py and inside it you import random.
random will not import the built-in random module but, rather, the random module you've created. This leads to the script executing the same statements twice (and also leads to other ugly errors if you tried and import something from random, like from random import randrange.)
Renaming the script leads to normal behavior.
Because your scripts is called random.py, so when you import random you are executing your script as well. Mind to name correctly your scripts.
your python script is named random.py so when you import random it import itself , in python when you import module it will run it.
therefor you get print twice.
rename your script or remove the import
The question is pretty simple: I need to move a piece of my code to the another file. In the main file, I'll do something like import not_main. Is is possible to run imported code as a part of the main file? Here's a simplified example:
__code
\__main.py
|__not_main.py
main.py content:
a = 5
import not_main
not_main.py content:
print a
When I'm running main.py, there is a error : NameError: name 'a' is not defined. How can I make it work? Thanks for any tips.
It's not possible to directly reference a variable in one module that's defined in another module unless you import that module first. Doesn't matter that it's the main module, this error would happen if you tried to do the same between any two modules. An imported module does not gain the scope of the module it's imported into.
There are possible workarounds, though I would caution using them if the code you're trying to separate out is fairly complex. But if you're intent on doing it, I'd suggest separating out any variables needed in both modules into a third module that only contains those variables. So the simple example you gave would turn into this:
cross_module_variables.py:
a = 5
main.py:
import not_main
not_main.py:
import cross_module_variables as cmv
print cmv.a
For more complex code you might need to assign the value of the variable in main after doing executing some code to produce the value. In that case you'll want to import cross_module_variables into the main module and assign a value to it. Course that variable has to be instantiated before it can be used in main so you'll have define the variable in cross_module_variable with some default value. So it would look something more like this:
cross_module_variables.py:
a = 0
main.py:
import cross_module_variables as cmv
cmv.a = 5
import not_main
not_main.py:
import cross_module_variables as cmv
print cmv.a
See this answer for more info on cross module variables.
With all that said, I would highly suggest you look at restructuring your code in some other sane way. It sounds like you're running all your code straight in modules instead of defining functions around discrete sections of code. You should look into ways of designing coherent functional programs.
I want to import a python module without adding its containing folder to the python path. I would want the import look like
from A import B as C
Due to the specific path that shall be used, the import looks like
import imp
A = imp.load_source('A', 'path')
C = A.B
This is quite unhandy with long paths and module names. Is there an easier way? Is there A way, where the module is not added to the local variables (no A)?
If you just don't want A to be visible at a global level, you could stick the import (imp.load_source) inside a function. If you actually don't want a module object at all in the local scope, you can do that too, but I wouldn't recommend it.
If module A is a python source file you could read in the file (or even just the relevant portion that you want) and run an exec on it.
source.py
MY_GLOBAL_VAR = 1
def my_func():
print 'hello'
Let's say you have some code that wants my_func
path = '/path/to/source.py'
execfile(path)
my_func()
# 'hello'
Be aware that you're also going to get anything else defined in the file (like MY_GLOBAL_VAR). Again, this will work, but I wouldn't recommend it
Someone looking at your code won't be able to see where my_func came from.
You're essentially doing the same thing as a from A import * import, which is generally frowned upon in python, because , you could be importing all sorts of things into your namespace that you didn't want. And even if it works now, if the source code changes, it could import names that shadow your own global symbols.
It's potentially a security hole, since you could be exec'ing an untrusted source file.
It's way more verbose than a regular python import.
I understand how to actually link python files, however, i don't understand how to get variable's from these linked files. I've tried to grab them and I keep getting NameError.
How do I go about doing this? The reason i want to link files is to simply neaten up my script and not make it 10000000000 lines long. Also, in the imported python script, do i have to import everything again? Another question, do i use the self function when using another scripts functions?
ie;
Main Script:
import sys, os
import importedpyfile
Imported Py File
import sys, os
I understand how to actually link python files, however, i don't
understand how to get variable's from these linked files. I've tried
to grab them and I keep getting NameError.
How are you doing that? Post more code. For instance, the following works:
file1.py
#!/usr/bin/env python
from file2 import file2_func, file2_variable
file2_func()
print file2_variable
file2.py:
#!/usr/bin/env python
file2_variable = "I'm a variable!"
def file2_func():
print "Hello World!"
Also, in the imported python script, do i have to import everything
again?
Nope, modules should be imported when the python interpreter reads that file.
Another question, do i use the self function when using another
scripts functions?
Nope, that's usually to access class members. See python self explained.
There is also more than one way to import files. See the other answer for some explanations.
I think what you are trying to ask is how to get access to global vars from on .py file without having to deal with namespaces.
In your main script, replace the call to import importedpyfile to say this instead
from importedpyfile import *
Ideally, you keep the code the way you have it. But instead, just reference those global vars with the importedpyfile namespace.
e.g.
import importedpyfile
importedpyfile.MyFunction() # calls "MyFunction" that is defined in importedpyfile.py
Python modules are not "linked" in the sense of C/C++ linking libraries into an executable. A Python import operation creates a name that refers to the imported module; without this name there is no (direct) way to access another module.