This question already has answers here:
How do I import other Python files?
(23 answers)
Closed 6 months ago.
file.py contains a function named function. How do I import it?
from file.py import function(a,b)
The above gives an error:
ImportError: No module named 'file.py'; file is not a package
First, import function from file.py:
from file import function
Later, call the function using:
function(a, b)
Note that file is one of Python's core modules, so I suggest you change the filename of file.py to something else.
Note that if you're trying to import functions from a.py to a file called b.py, you will need to make sure that a.py and b.py are in the same directory.
Do not write .py when importing.
Let file_a.py contain some functions inside it:
def f():
return 1
def g():
return 2
To import these functions into file_z.py, do this:
from file_a import f, g
If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:
Let's say you have following package structure in your python project:
in - com.my.func.DifferentFunction python file you have some function, like:
def add(arg1, arg2):
return arg1 + arg2
def sub(arg1, arg2) :
return arg1 - arg2
def mul(arg1, arg2) :
return arg1 * arg2
And you want to call different functions from Example3.py, then following way you can do it:
Define import statement in Example3.py - file for import all function
from com.my.func.DifferentFunction import *
or define each function name which you want to import
from com.my.func.DifferentFunction import add, sub, mul
Then in Example3.py you can call function for execute:
num1 = 20
num2 = 10
print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))
Output:
add : 30
sub : 10
mul : 200
Method 1. Import the specific function(s) you want from file.py:
from file import function
Method 2. Import the entire file:
import file as fl
Then, to call any function inside file.py, use:
fl.function(a, b)
You can call the function from a different directory as well, in case you cannot or do not want to have the function in the same directory you are working. You can do this in two ways (perhaps there are more alternatives, but these are the ones that have worked for me).
Alternative 1
Temporarily change your working directory
import os
os.chdir("**Put here the directory where you have the file with your function**")
from file import function
os.chdir("**Put here the directory where you were working**")
Alternative 2
Add the directory where you have your function to sys.path
import sys
sys.path.append("**Put here the directory where you have the file with your function**")
from file import function
To fix
ModuleNotFoundError: No module named
try using a dot (.) in front of the filename to do a relative import:
from .file import function
Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:
from directory_name.file_name import function_name
And later be used: function_name()
Rename the module to something other than 'file'.
Then also be sure when you are calling the function that:
1)if you are importing the entire module, you reiterate the module name when calling it:
import module
module.function_name()
or
import pizza
pizza.pizza_function()
2)or if you are importing specific functions, functions with an alias, or all functions using *, you don't reiterate the module name:
from pizza import pizza_function
pizza_function()
or
from pizza import pizza_function as pf
pf()
or
from pizza import *
pizza_function()
First save the file in .py format (for example, my_example.py).
And if that file have functions,
def xyz():
--------
--------
def abc():
--------
--------
In the calling function you just have to type the below lines.
file_name: my_example2.py
============================
import my_example.py
a = my_example.xyz()
b = my_example.abc()
============================
append a dot . in front of a file name if you want to import this file which is in the same directory where you are running your code.
For example, I'm running a file named a.py and I want to import a method named addFun which is written in b.py, and b.py is there in the same directory
from .b import addFun
Inside MathMethod.Py.
def Add(a,b):
return a+b
def subtract(a,b):
return a-b
Inside Main.Py
import MathMethod as MM
print(MM.Add(200,1000))
Output:1200
You don't have to add file.py.
Just keep the file in the same location with the file from where you want to import it. Then just import your functions:
from file import a, b
Solution1: In one file myfun.py define any function(s).
# functions
def Print_Text():
print( 'Thank You')
def Add(a,b):
c=a+b
return c
In the other file:
#Import defined functions
from myfun import *
#Call functions
Print_Text()
c=Add(1,2)
Solution2: if this above solution did not work for Colab
Create a foldermyfun
Inside this folder create a file __init__.py
Write all your functions in __init__.py
Import your functions from Colab notebook from myfun import *
You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.
Any of the above solutions didn't work for me. I got ModuleNotFoundError: No module named whtever error.
So my solution was importing like below
from . import filename # without .py
inside my first file I have defined function fun like below
# file name is firstFile.py
def fun():
print('this is fun')
inside the second file lets say I want to call the function fun
from . import firstFile
def secondFunc():
firstFile.fun() # calling `fun` from the first file
secondFunc() # calling the function `secondFunc`
Suppose the file you want to call is anotherfile.py and the method you want to call is method1, then first import the file and then the method
from anotherfile import method1
if method1 is part of a class, let the class be class1, then
from anotherfile import class1
then create an object of class1, suppose the object name is ob1, then
ob1 = class1()
ob1.method1()
in my case i named my file helper.scrap.py and couldn't make it work until i changed to helper.py
in my main script detectiveROB.py file i need call passGen function which generate password hash and that functions is under modules\passwordGen.py
The quickest and easiest solution for me is
Below is my directory structure
So in detectiveROB.py i have import my function with below syntax
from modules.passwordGen import passGen
Just a quick suggestion,
Those who believe in auto-import by pressing alt+ enter in Pycharm and cannot get help.
Just change the file name from where you want to import by:
right-clicking on the file and clicking on refactor-> rename.
Your auto-import option will start coming up
I use Python 2.7. I'm trying to run my UI-automation script, but I got ImportError.
I have at least 30 Classes with methods. I want to have these methods in each and any class that's why I created BaseClass(MainClass) and created objects of all my classes. Please advise what should I do in this case or how I can solve this problem.
Here the example what similar to my code.
test_class/baseclass.py
from test_class.first_class import FirstClass
from test_class.second_class import SecondClass
class MainClass:
def __init__(self):
self.firstclass = FirstClass()
self.secondclass = SecondClass()
test_class/first_class.py
from test_class.baseclass import MainClass
class FirstClass(MainClass):
def __init__(self):
MainClass.__init__(self)
def add_two_number(self):
return 2 + 2
test_class/second_class.py
from test_class.baseclass import MainClass
class SecondClass(MainClass):
def __init__(self):
MainClass.__init__(self)
def minus_number(self):
return self.firstclass.add_two_number() - 10
if __name__ == '__main__':
print(SecondClass().minus_number())
When I run the last file I get this error
Traceback (most recent call last):
File "/Users/nik-edcast/git/ui-automation/test_class/second_class.py", line 1, in <module>
from test_class.baseclass import MainClass
File "/Users/nik-edcast/git/ui-automation/test_class/baseclass.py", line 1, in <module>
from test_class.first_class import FirstClass
File "/Users/nik-edcast/git/ui-automation/test_class/first_class.py", line 1, in <module>
from test_class.baseclass import MainClass
ImportError: cannot import name MainClass
check this line: from test_class.baseclass import MainClass -> it seems like all other imports had a '_' between the names like second_class. So try maybe to write base_class. who knows might work
Are you proabably running your code like python test_class/second_class.py. If you just do this then python will think the base directory to find modules is ./test_class. So when you import the test_class package python will start looking for a folder called ./test_class/test_class to find the sub-modules. This directory doesn't exist and so the import fails. There are several ways that you can tell python how to correctly find your modules.
Using PYTHONPATH
One way to get around this is to set PYTHONPATH before starting python. This is just an environment variable with which you can tell python where to look for your modules.
eg.
export PYTHONPATH=/path/to/your/root/folder
python test_class/second_class.py
Using the -m switch for python
Be default python treats the directory of the main module as the place to look for other modules. However, if you use -m python will fall back to looking in the current directory. But you also need to specify the full name of the module you want to run (rather than as a file). eg.
python -m test_class.second_class
Writing a root entry point
In this we just define your main module at the base level (the directory that contains test_class. Python will treat this folder as the place to look for user modules and will find everything appropriately. eg.
main.py (in /path/to/your/root/folder)
from test_class.second_class import SecondClass
if __name__ == '__main__':
print(SecondClass().minus_number())
at the command line
python main.py
You could try importing the full files instead of using from file import class. Then you would only need to add the file name before referencing something from another file.
thank you all, this problem was solved
but I don't know What is the different between them
wrong script :
def func(module) :
cwd = os.getcwd()
os.chdir(module['path'])
tmp = __import__(module['name'])
os.chdir(cwd)
working well script :
def func(module) :
sys.path.append(module['path'])
tmp = __import__(module['name'])
...
happy new year :)
============================================================
Hello I need to import dynamically in python script
when I try __import__() outside of a function
ex)
__import__('myModule')
it does work, but when I try it within a function
ex )
def func() :
__import__('myModule')
func()
I get an ImportError: ImportError: No module named myModule
How can I use __import__() in function??
I think what you want to use here is the following:
from importlib import import_module
def func():
import_module('myModule')
When Python starts, the script’s directory is put at the front of sys.path, so that import finds things in it. In some cases (not, for example, python foo/bar.py), what is put there is an empty string, which means “search the current working directory”. Only in that case will os.chdir affect import in the way you expected.
I would like to separate my functions into different files like I do with c++ (a driver file and a file for different categories of functions that I end up linking together upon compilation).
Let's suppose I want to create a simple 'driver' file which launches the main program and a 'function' file which includes simple functions which are called by the driver and other functions within the 'function' file.
How should I do this? Since python is not compiled, how do I link files together?
You can import modules. Simply create different python files and import them at the start of your script.
For example I got this function.py file :
def func(a, b):
return a+b
And this main.py file:
import function
if __name__ == "__main__":
ans = function.func(2, 3)
print(ans)
And that is it! This is the official tutorial on importing modules.
You can import any Python file simply by typing:
import filename
But in this case you have to type the file name each time you want to use it. For example, you have to use filename.foo to use the specific function foo inside that file. However, you can also do the following:
from function import *
In this case all you have to do is to directly type your commands without filename.
A clear example:
If you are working with the Python turtle by using import turtle then each time you have to type turtle.foo. For example: turtle.forward(90), turtle.left(90), turtle.up().
But if you use from turtle import * then you can do the same commands without turtle. For example: forward(90), left(90), up().
At the beginning of driver.py, write:
import functions
This gives you access to attributes defined in functions.py, referenced like so:
functions.foo
functions.bar(args)
...
I am having a problem that may be quite a basic thing, but as a Python learner I've been struggling with it for hours. The documentation has not provided me with an answer so far.
The problem is that an import statement included in a module does not seem to be executed when I import this module from a python script. What I have is as follows:
I have a file project.py (i.e. python library) that looks like this:
import datetime
class Project:
""" This class is a container for project data """
title = ""
manager = ""
date = datetime.datetime.min
def __init__( self, title="", manager="", date=datetime.datetime.min ):
""" Init function with some defaults """
self.title = title
self.manager = manager
self.date = date
This library is later used in a script (file.py) that imports project, it starts like this:
import project
print datetime.datetime.min
The problem then arises when I try to execute this script with Python file.py. Python then complains with the folliwing NameError:
Traceback (most recent call last):
File "file.py", line 3, in <module>
print datetime.datetime.min
NameError: name 'datetime' is not defined
This actually happens also if I try to make the same statements (import and print) directly from the Python shell.
Shouldn't the datetime module be automatically imported in the precise moment that I call import project?
Thanks a lot in advance.
The datetime module is only imported into the project namespace. So you could access it as project.datetime.datetime.min, but really you should import it into your script directly.
Every symbol (name) that you create in your project.py file (like your Project class) ends up in the project namespace, which includes things you import from other modules. This isn't as inefficient as it might seem however - the actual datetime module is still only imported once, no matter how many times you do it. Every time you import it subsequent to the first one it's just importing the names into the current namespace, but not actually doing all the heavy lifting of reading and importing the module.
Try thinking of the import statement as roughly equivalent to:
project = __import__('project')
Effectively an import statement is simply an assignment to a variable. There may be some side effects as the module is loaded, but from inside your script all you see is a simple assignment to a name.
You can pull in all the names from a module using from project import *, but don't do that because it makes your code much more brittle and harder to maintain. Instead either just import the module or exactly the names you want.
So for your code something like:
import datetime
from project import Project
is the sort of thing you should be doing.