Call a function from another file?

1,546,354

Solution 1

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.

Solution 2

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

Solution 3

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:

Python package and file structure

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

Solution 4

You can do this in 2 ways. First is just to import the specific function you want from file.py. To do this use

from file import function

Another way is to import the entire file

import file as fl

Then you can call any function inside file.py using

fl.function(a,b)

Solution 5

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
Share:
1,546,354
user2977230
Author by

user2977230

Updated on September 28, 2021

Comments

  • user2977230
    user2977230 over 2 years

    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?

  • user2977230
    user2977230 over 10 years
    The "file" was just a placeholder for the question I am asking, not the actual file name. Thank you though. I will try this and get back to you.
  • m3nda
    m3nda almost 9 years
    I don't know if my fail is about python versions. What i do choosing this example is import fn (without extension) and using them directly on the main file fn.my_funcion(). When i use import fn.py tries to load py.py file, wich doesn't exist. Using from fn.py import funcname didn't work too. Thank you.
  • DarkRose
    DarkRose almost 9 years
    I tried this, but it is still showing the error: Has it got anything to do with Python 3, or is a general problem?
  • Dimitar Marinov
    Dimitar Marinov over 8 years
    you can also import *
  • Tom
    Tom about 8 years
    @GamesBrainiac, what if the file you want to import functions from is in a different directory? Can I include the filepath preceeding the filename, or is there something more complicated?
  • Games Brainiac
    Games Brainiac about 8 years
    @Tom You have to add that path to the PYTHONPATH variable if it is not already in there.
  • Nirvan Sengupta
    Nirvan Sengupta over 7 years
    Is there a way to import functions from a.py to a file b.py if they are not in the same directory?
  • Karlo
    Karlo about 7 years
    @DimitarMarinov With * replaced by the filename?
  • Dimitar Marinov
    Dimitar Marinov about 7 years
    @Karlo, no, just *
  • Francisco Gutiérrez
    Francisco Gutiérrez about 7 years
    using "import *" is considered a bad practice. Explicit is better than implicit.
  • Mohan
    Mohan almost 7 years
    Oh sure it doesn't. I didn't meant to type .py It's a typo
  • Jason
    Jason almost 7 years
    newbies try "import file", which should execute only once (singleton)
  • Aditya C
    Aditya C almost 7 years
    If a.py is in a folder say fol1, then how shall it be imported? @dimitar-marinov
  • GoodDeeds
    GoodDeeds almost 7 years
    @AdityaC add the folder to your PYTHONPATH is one way
  • quantik
    quantik almost 7 years
    Do you have to import all dependencies from file that are used in function as well?
  • alex
    alex about 6 years
    In Python 2 it looks like this either (a) executes the entire script you're referencing with from foo import ... or (b) does not work if foo.py has references to the argparse library.
  • Birish
    Birish about 5 years
    isn't it the same as adding path to PYTHONPATH?
  • jdhao
    jdhao almost 5 years
    glob import is discouraged.
  • duXing
    duXing over 4 years
    Dimitar Marinov means this: from a import *
  • JeffCharter
    JeffCharter over 4 years
    I don't think you can have . or - in the file names
  • 0xc0de
    0xc0de over 3 years
    Can't resist to point out the Java like file structure... com.my.example.. kinda pokes into my eyes, though it might be just me.
  • abanmitra
    abanmitra over 3 years
    :)...actually I am from a java background
  • Pe Dro
    Pe Dro over 3 years
    WHat should be the working directory to run the code ?
  • abanmitra
    abanmitra over 3 years
    I am executing this addition or multiplication function from the "Example3.py" file.
  • Pieter21
    Pieter21 over 3 years
    This is the one that worked for me in a special case where I wanted to 'borrow-call' some external code without copy or modification.
  • Antti
    Antti about 3 years
    I would rate this a correct answer. Concise and clear solution.
  • Haha
    Haha about 3 years
    Any explanation about this please ?
  • Shubh
    Shubh about 3 years
    saved my day, thanks . '.' points to current working directory
  • nuKs
    nuKs about 3 years
    @DarkRose Same for me, I fixed it by changing the order of the imports within init.py file, making sure root dependencies were loaded after their transitive dependencies.
  • PatrickT
    PatrickT over 2 years
    Didn't work with a hyphen in the filename, e.g. from fil-e import *.
  • Shiri
    Shiri about 2 years
    @jdhao Thanks for the constructive alternative.