Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function from another file?

Set_up: I have a .py file for each function I need to use in a program.

In this program, I need to call the function from the external files.

I've tried:

from file.py import function(a,b) 

But I get the error:

ImportError: No module named 'file.py'; file is not a package

How do I fix this problem?

like image 375
user2977230 Avatar asked Dec 01 '13 06:12

user2977230


People also ask

How do you call a function in another file?

To use the functions written in one file inside another file include the import line, from filename import function_name . Note that although the file name must contain a . py extension, . py is not used as part of the filename during import.

How do you call a function from another directory in Python?

First make utils_dir as python package: simply add init.py in the directory. b). Then, add path of parent folder of utils_dir to PYTHONPATH environment variable. You can add this line into your .


2 Answers

There isn't any need to add file.py while importing. Just write from file import function, and then call the function using function(a, b). The reason why this may not work, is because file is one of Python's core modules, so I suggest you change the name of your file.

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.

like image 116
Games Brainiac Avatar answered Sep 18 '22 12:09

Games Brainiac


First of all you do not need a .py.

If you have a file a.py and inside you have some functions:

def b():   # Something   return 1  def c():   # Something   return 2 

And you want to import them in z.py you have to write

from a import b, c 
like image 45
Salvador Dali Avatar answered Sep 20 '22 12:09

Salvador Dali