How do I call a function from another .py file?
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.
How to call function from another .py file in python?
Probably you are calling inside your file2.py
your function myfunction()
when you do
from file2 import *
you are loading every definitions (class, def, etc), and of course, every function called inside that .py.
To avoid this problem you can call your function myfunction() in your file2.py inside this scope:
if __name__ == '__main__':
myfunction()
in this way it will not be executed when imported, but only if the file2.py is executed directly:
python3 file2.py
Call function from another file without import clause?
Without any importing this is not possible, but what you can do is, import a module, and call a function of a submodule of that module. Like this:
import tmpapp
def kakikomi(request):
f = tmpapp.forms.KakikomiForm()
Python Calling Function from Another File
Let us have two files in the same directory. Files are called main.py
and another.py
.
First write a method in another.py
:
def do_something():
return "This is the do something method"
Then call the method from main.py
. Here is the main.py
:
import another
print another.do_something()
Run main.py
and you will get output like this:
This is the do something method
N.B.: The above code is being executed using Python 2.7 in Windows 10.
Related Topics
Tkinter: How to Use After Method
Saving an Object (Data Persistence)
What Are the Advantages of Numpy Over Regular Python Lists
How to Check If a List Is Empty
Does Python Have "Private" Variables in Classes
How to Play an Mp3 With Pygame
Installing Python Module Within Code
Remove All the Elements That Occur in One List from Another
How to Add a New Column to an Existing Dataframe
How to Properly Ignore Exceptions
How to Save and Load Cookies Using Python + Selenium Webdriver
How to Replace Nans by Preceding or Next Values in Pandas Dataframe
How to Understand Closure in a Lambda