Call function in file python

Calling Functions from Other Files

User-defined functions can be called from other files. A function can be called and run in a different file than the file where the function is defined.

If a new file called myfunctions.py is created and contains two function definitions, plustwo() and falldist() , the functions plustwo() and falldist() can be used by a separate script as long as the file and function names are imported in the separate script first. It is essential that the file which contains the function definitions ends in the .py extension. Without a .py extension, the file where the functions are defined can not be imported. Inside the file myfuctions.py, two functions are defined using the code below.

# myfunctions.py def plustwo(n): out = n + 2 return out def falldist(t,g=9.81): d = 0.5 * g * t**2 return d 

This file, myfunctions.py can be imported into another script (another .py file), or Jupyter Notebook.

Remember the file that contains the function definitions and the file calling the functions must be in the same directory.

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.

The general syntax to import and call a function from a separate file is below:

from function_file import function_name function_name(arguments) 

An example using this syntax with the myfunctions.py file and the function plustwo() is below:

from myfunctions import plustwo

plustwo(3)

Источник

SOLVED: Calling a function from another file in Python

Different methods for calling a function from another file in Python

When we wish to call a function from another file in Python, we have different scenarios to achieve our goal.

  • Calling a function from another file
  • Calling a function containing arguments from another python file
  • Calling a function present in a file with a different directory
  • Importing all functions from another Python file
  • Calling a function without using the import function

Example-1: Calling a function from another file

In this scenario, we are calling a function from another file. Let us take a compute.py file having a function interest to compute the simple interest of given principal and duration. We will then write a demo.py file that has saving function, which when called makes call to interest function to compute simple interest.
compute.py

# Function to compute simple interest at fixed rate of 5% def interest(): p=int(input("Enter the principal amount")) n=int(input("Enter the number of years")) print("Computing simple interest at rate of 5%") r=5 si=(p*r*n)/100 return si 
from compute import interest def saving(): print("Interest accrued is",interest()) saving() 
Enter the principal amount 1000 Enter the number of years 2 Computing simple interest at rate of 5% Interest accrued is 100.0 

Example-2: Calling Function containing arguments from another python file

In this scenario, we are calling a function from another file but with the arguments. Let us firstly write two python files compute.py and demo.py. We will write a function interest to compute simple interest when we pass amount and number of years. The rate is fixed as 5%. Hence, the function will compute simple interest and return the amount to the calling function.
compute.py

# Function to compute simple interest at fixed rate of 5% def interest(p,n): print("Computing simple interest at rate of 5%") r=5 si=(p*r*n)/100 return si 
from compute import interest # Get input from the user p=int(input("Enter the principal amount")) n=int(input("Enter the number of years")) # Calling a function of compute.py file with p and n as an arguments print("Interest accrued for the principal",p, "for",n, "years at the rate of 5% is",interest(p,n)) 
Enter the principal amount 1000 Enter the number of years 2 Computing simple interest at rate of 5% Interest accrued for the principal 1000 for 2 years at the rate of 5% is 100.0 

Example-3: Calling function present in a file with a different directory

In this scenario, we are calling a function from another file in different directory. Let us save the file compute.py inside the folder bank. Whereas, demo.py is saved outside the folder bank. Hence, we are accessing the file from the module bank stored in the different directory. In this case, only the import statement requires the modification. The way function is called remains same.

bank/compute.py

# Function to compute simple interest at fixed rate of 5% def interest(p,n): print("Computing simple interest at rate of 5%") r=5 si=(p*r*n)/100 return si 
from bank.compute import interest # Get input from the user p=int(input("Enter the principal amount")) n=int(input("Enter the number of years")) # Calling a function of compute.py file with p and n as an arguments print("Interest accrued for the principal",p, "for",n, "years at the rate of 5% is",interest(p,n)) 
Enter the principal amount 1000 Enter the number of years 2 Computing simple interest at rate of 5% Interest accrued for the principal 1000 for 2 years at the rate of 5% is 100.0 

Example-4: Importing all functions from another Python file

In this scenario, Let us take the compute.py file but with one more function added to compute compound interest. Here, we will import all the functions present in compute.py file. The compute.py contains two functions to compute simple interest and compound interest. We will then make a call to a function demo.py file.

# Function to compute simple interest at fixed rate of 5% def interest(p,n): print("Computing simple interest at rate of 5%") r=5 si=(p*r*n)/100 return si # Function to compute Compound interest at fixed rate of 5% def compoundinterest(p,n): print("Computing Compound interest at rate of 5%") r=5 ci=p*pow(1+r/100,n)-p return ci 
from compute import * # Get input from the user p=int(input("Enter the principal amount")) n=int(input("Enter the number of years")) # Calling a function of compute.py file with p and n as an arguments print("Simple Interest accrued for the principal",p, "for",n, "years at the rate of 5% is",interest(p,n)) print("Compound Interest accrued for the principal",p, "for",n, "years at the rate of 5% is",compoundinterest(p,n)) 
Enter the principal amount 1000 Enter the number of years 5 Computing simple interest at rate of 5% Simple Interest accrued for the principal 1000 for 5 years at the rate of 5% is 250.0 Computing Compound interest at rate of 5% Compound Interest accrued for the principal 1000 for 5 years at the rate of 5% is 276.2815625000003 

Example-5: Call a function without using the import statement

In this scenario, we will not use import statement, rather use importlib and use the function from the file compute.py . Let us assume, our project structure is something like as shown below.
computeproject->computelib->compute.py
computeproject->demo.py

# Function to compute simple interest at fixed rate of 5% def interest(p,n): print("Computing simple interest at rate of 5%") r=5 si=(p*r*n)/100 print("Simple Interest accured for the principal",p, "for",n, "years at the rate of 5% is",si) 
import importlib from inspect import isfunction def call_func(full_module_name, func_name, *argv): module = importlib.import_module(full_module_name) for attribute_name in dir(module): attribute = getattr(module, attribute_name) if isfunction(attribute) and attribute_name == func_name: attribute(*argv) call_func('compute', 'interest', 1000,5) 
Computing simple interest at rate of 5% Interest accured for the principal 1000 for 5 years at the rate of 5% is 250.0

Summary

The knowledge of Calling a function from another file in Python is very useful while working on real and practical world applications. It helps in re-usability and data abstraction. In many situations, we will need to call a function that is used in many other files of a project and is lying in some common functionality file. In this tutorial, we covered the different scenario to call a function lying in another file and directory with an example. All in all, this tutorial, covers everything that you need to know in order to understand calling a function from another file in Python.

Источник

Python – call a function from another file

As a Python programmer, you may want to call a function from another file in Python. By doing so, you do not have to rewrite your code or copy it into your existing code base.

We will use Python 3.10.4 with Visual Studio Code as our code editor for this guide. But, of course, you are free to use the code editor of your choice.

Scripts, Functions, and Methods – a quick recap

Learning exactly what scripts, functions, and methods mean can simplify the process of calling a function from another file in Python.

  • Every time you write Python code, you are writing a script. These scripts are then executed in Python Shell, and you get the output.
  • Functions are reusable codes that you can use when coding. This simplifies your approach to coding apps or websites.
  • Lastly, we have methods included in packages such as Numpy, Matplotlib, etc. These methods are pre-defined and provide the functions used on Python objects.

Step 1: Create a script with functions

The first step is to create a script with functions. You can skip to the second step if you have already created a script.

For this tutorial, we will create file.py which contains four functions: addition(), subtract(), multiply() and Hello_world().

The code for it is as below.

#here we create a function that we want to call from another file def addition(a,b): #code for adding return a +b def Hello_World(): #Hi world! return "Hello, World!" def subtract(a,b): if a > b: return a - b else: return b - a def multiply(a,b): return a * b;

Step 2: Create the file you want to call the function from

Next, we need to create another script where we call functions from the first file. Let’s name the new script file2.py.

#import everything from file.py from file import * #storing Hello_world() return value to world variable world = Hello_World() #print world varaible to the screen print(world) 

from file import * tells the compiler to import all the available functions in file.py.

Next, we call Hello_World() function defined in file.py and print its value to the screen.

You can also import the functions by assigning them a variable and then accessing it through it.

And to access the functions, you need to use the following notation.

Step 3: Call selected functions

Similarly, you can call other functions in file2.py from file.py.

Let’s look at another example, but this time, we will import selected functions. Let’s name this script: file3.py

#importing selected functions from file.py from file import addition, subtract #using the addition function to add two numbers add_result = addition(3,5) #using the substract function to subtract two numbers sub_result = subtract(5,3) #printing out result print(add_result) print(sub_result)

To import selected functions, you need to separate them using a comma, as shown in the line from file import addition, subtract

The output is shown below.

Things to keep in mind when calling functions

You can import multiple functions from different files as well.

If you are importing functions from a file not in the same folder, you need to use the exact path from the root directory.

So, if you have your file.py inside two directories, you must import it using the following command.

from rootfolder.folder1.folder2.file import addition, subtract

That’s it! You have successfully learned how to call a function from another file in Python.

Источник

Читайте также:  Пример 1
Оцените статью