I'm working on my first project and am trying to figure out how something works. If I have a module that store some functions I will reference in my main program that depend on another module, where do I include the import statement?
For example:
# Title: func.py
import os
def my_function(path):
if not os.path.isfile(path):
parser.error(f'The file {path} does not exist.')
Do I include import os here, or can I simply have it in the main document?
You must import the module in the file that references the module. So if you have a file that somewhere calls os.path.isfile, you need to import os at the top of that file.
-- comment by larsks
How can I use functions that I have created before, in different python files and projects? for example functions that I have created in project A I want to use in project B.
You need to import like any other library you import in your python file. For example if you have a python script A.py and you are writing another python script B.py and you want to use some methods of A then you just need to import like this:
from A import *
Will import all the methods of A.
you can import a specific method only like this:
from A import method1
Thanks hope it helps
A.py contains
def myFunction():
print("Hello World")
you can call this function in your B.py
by simply importing it
B.py contains
import A
A.myFunction()
I have a file called hotel_helper.py from which I want to import a function called demo1, but I am unable to import it.
My hotel_helper.py file:
def demo1():
print('\n\n trying to import this function ')
My other file:
from hotel.helpers.hotel_helper import demo1
demo1()
but I get:
ImportError: cannot import name 'demo1' from 'hotel.helpers.hotel_helper'
When I import using from hotel.helpers.hotel_helper import * instead of from hotel.helpers.hotel_helper import demo1 it works and the function gets called. I tried importing the whole file with from hotel.helpers import hotel_helper and then call the function with hotel_helper.demo1() and it works fine. I don't understand what's wrong in first method. I want to directly import function rather using * or importing the whole file.
If you filename is hotel_helper.py you have to options how to import demo1:
You can import the whole module hotel_helper as and then call your func:
import hotel_helper as hh
hh.demo1()
You can import only function demo1 from module as:
from hote_helpers import demo1
demo1()
From your fileName import your function
from hotel.helpers import demo1
demo1()
You can import a py file with the following statement:
# Other import
import os
import sys
if './hotel' not in sys.path:
sys.path.insert(0, './hotel')
from hotel import *
NOTE:
For IDE like PyCharm, you can specify the import path using the Project Structure setting tab (CTRL+ALT+S)
Helpful stack overflow questions [maybe off topic]:
What is the right way to create project structure in pycharm?
Manage import with PyCharm documentation:
https://www.jetbrains.com/help/pycharm/configuring-project-structure.html
This is probably a duplicate of: https://stackoverflow.com/posts/57944151/edit
I created two files (defdemo.py and rundefdemo.py) from your posted 2 files and substituted 'defdemo' for 'hotel.helpers.hotel_helper' in the code. My 2 files are in my script directory for Python 3.7 on windows 10 and my script directory is in the python path file python37._pth. It worked.
defdemo.py
def demo1():
print('\n\n trying to import this function ')
rundefdemo.py
from defdemo import demo1
demo1()
output
trying to import this function
I was able to solve the issue, it was related to some imports I was making in my file, when I removed all the import statement in my hotel_helper.py ,the code started working as expected , Still I don't understand reason why the issue was occurring. anyway it works.
This ImportError can also arise when the function being imported is already defined somewhere else in the main script (i.e. calling script) or notebook, or when it is defined in a separate dependency (i.e. another module). This happens most often during development, when the developer forgets to comment out or delete the function definition in the body of a main file or nb after moving it to a module.
Make sure there are no other versions of the function in your development environment and dependencies.
I am working on project euler and wanted to time all of my code. What I have is directory of files in the form 'problemxxx.py' where xxx is the problem number. Each of these files has a main() function that returns the answer. So I have created a file called run.py, located in the same directory as the problem files. I am able to get the name of the file through command prompt. But when I try to import the problem file, I continue to get ImportError: No module named problem. Below is the code for run.py so far, along with the command prompt used.
# run.py
import sys
problem = sys.argv[1]
import problem # I have also tired 'from problem import main' w/ same result
# will add timeit functions later, but trying to get this to run first
problem.main()
The command prompts that I have tried are the following: (both of which give the ImportError stated above)
python run.py problem001
python run.py problem001.py
How can I import the function main() from the file problem001.py? Does importing not work with the file name stored as a variable? Is there a better solution than trying to get the file name through command prompt? Let me know if I need to add more information, and thank you for any help!
You can do this by using the __import__() function.
# run.py
import sys
problem = __import__(sys.argv[1], fromlist=["main"]) # I have also tired 'from problem import main' w/ same result
problem.main()
Then if you have problem001.py like this:
def main():
print "In sub_main"
Calling python run.py problem001 prints:
In sub_main
A cleaner way to do this (instead of the __import__ way) is to use the importlib module. Your run.py needs to changes:
import importlib
problem = importlib.import_module(sys.argv[1])
Alternatives are mentioned in this question.
For sure! You can use __ import_ built-in function like __import__(problem). However this is not recommended to use, because it is not nice in terms of coding-style. I think if you are using this for testing purposes then you should use unittest module, either way try to avoid these constructions.
Regards
You can use exec() trick:
import sys
problem = sys.argv[1]
exec('import %s' % problem)
exec('%s.main()' % problem)
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)
Note: If you are working with Jupiter notebook you may need to change path for method 1. :
os.chdir('/')
see https://stackoverflow.com/a/35665295/1984636
And for method 2:
import sys
sys.path.append('../src/')
see https://stackoverflow.com/a/55623567/1984636
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