How to Call a Function from Another File in Python?

In this tutorial, I will explain how to call a function from another file in Python. Recently someone asked about calling a function from another file, which made me research this topic and I found several ways to achieve this task. I will share my findings with suitable examples and screenshots.

Call a Function from Another File in Python

Let’s assume we are working on a “USA Weather Analysis” project. We will create two files: main.py and weather_utils.py. The weather_utils.py file will contain utility functions related to weather data processing, and main.py will call these functions.

Read How to Read an Excel File in Python?

Step 1: Create weather_utils.py

First, we create a file named weather_utils.py and define a function that processes weather data:

# weather_utils.py

def get_average_temperature(temperatures):
    """
    Calculate the average temperature from a list of temperatures.

    Parameters:
    temperatures (list): List of temperature readings (in Fahrenheit).

    Returns:
    float: Average temperature.
    """
    if not temperatures:
        return 0
    return sum(temperatures) / len(temperatures)

def get_temperature_trend(temperatures):
    """
    Determine the temperature trend (increasing, decreasing, or stable).

    Parameters:
    temperatures (list): List of temperature readings (in Fahrenheit).

    Returns:
    str: Temperature trend ('increasing', 'decreasing', 'stable').
    """
    if temperatures[-1] > temperatures[0]:
        return 'increasing'
    elif temperatures[-1] < temperatures[0]:
        return 'decreasing'
    else:
        return 'stable'

Check out How to Import a Python File from the Same Directory?

Step 2: Create main.py

Now, we create another file named example.py where we will call the functions defined in weather_utils.py:

# example.py

from weather_utils import get_average_temperature, get_temperature_trend

def main():
    # Sample temperature data for New York City
    nyc_temperatures = [55, 57, 60, 62, 65, 64, 63]

    # Calculate average temperature
    avg_temp = get_average_temperature(nyc_temperatures)
    print(f"The average temperature in NYC is {avg_temp:.2f}°F.")

    # Determine temperature trend
    trend = get_temperature_trend(nyc_temperatures)
    print(f"The temperature trend in NYC is {trend}.")

if __name__ == "__main__":
    main()

Explanation

  1. Importing Functions: In example.py, we import the get_average_temperature and get_temperature_trend functions from weather_utils.py.
  2. Using Imported Functions: We call these functions with sample temperature data for New York City.
  3. Output: The script calculates and prints the average temperature and the temperature trend.

I executed the above example code and added the screenshot below.

Call a Function from Another File in Python

Read How to Get File Size in Python?

Handle Relative Imports

In larger projects, you might have a more complex directory structure. For example:

usa_weather_analysis/
│
├── main.py
└── utils/
    └── weather_utils.py

In this case, you need to adjust the import statements to reflect the directory structure. In main.py:

from utils.weather_utils import get_average_temperature, get_temperature_trend

Example

Let’s enhance our example by fetching real-time weather data. We will use the requests library to get weather data from an API.

Check out How to Overwrite a File in Python?

Step 1: Install requests

First, install the requests library if you haven’t already:

pip install requests

Step 2: Update weather_utils.py

Add a function to fetch weather data from an API:

# weather_utils.py

import requests

def fetch_weather_data(city):
    """
    Fetch current weather data for a given city using OpenWeatherMap API.

    Parameters:
    city (str): City name.

    Returns:
    dict: Weather data.
    """
    api_key = 'your_api_key_here'
    url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=imperial'
    response = requests.get(url)
    return response.json()

Read How to Rename Files in Python?

Step 3: Update main.py

Modify main.py to fetch and process real-time weather data:

# main.py

from weather_utils import get_average_temperature, get_temperature_trend, fetch_weather_data

def main():
    city = 'New York'
    weather_data = fetch_weather_data(city)
    temperatures = [weather_data['main']['temp']]

    # Calculate average temperature
    avg_temp = get_average_temperature(temperatures)
    print(f"The current temperature in {city} is {avg_temp:.2f}°F.")

    # Determine temperature trend
    trend = get_temperature_trend(temperatures)
    print(f"The temperature trend in {city} is {trend}.")

if __name__ == "__main__":
    main()

Explanation

  1. Fetching Weather Data: We added the fetch_weather_data function to get real-time weather data from OpenWeatherMap API.
  2. Processing Data: The script fetches the current temperature for New York City and processes it to determine the trend.

Check out How to Check if a File is Empty in Python?

Error Handling and Validation

When calling functions from another file, it’s crucial to handle potential errors gracefully. For instance, the API call might fail, or the data might be incomplete. Update fetch_weather_data to include error handling:

# weather_utils.py

def fetch_weather_data(city):
    api_key = 'your_api_key_here'
    url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=imperial'
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for HTTP errors
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
        return None

Update main.py for Error Handling

# main.py

def main():
    city = 'New York'
    weather_data = fetch_weather_data(city)
    if weather_data:
        temperatures = [weather_data['main']['temp']]

        # Calculate average temperature
        avg_temp = get_average_temperature(temperatures)
        print(f"The current temperature in {city} is {avg_temp:.2f}°F.")

        # Determine temperature trend
        trend = get_temperature_trend(temperatures)
        print(f"The temperature trend in {city} is {trend}.")
    else:
        print("Failed to fetch weather data.")

if __name__ == "__main__":
    main()

Read How to Get File Name Without Extension in Python?

Conclusion

In this article, I explained how to call a function from another file in Python. I discussed steps to call function from another file in Python, how to handle relative imports step-by-step with example. I also covered error handling and validation.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.