Organization in your code- Using functions, classes, e.t.c, is a crucial factor in developing maintainable and readable Python code. Besides, features such as functions help develop reusable code. That way, we do not need to repeat writing code with the same functionality within a module or across modules.

When we want to achieve maintainable, readable, and reusable code, we may be obliged to use some function in another function in Python. Would calling a function within a function be possible?

A function can call another function and use the imported functionality from the called function. The called function can be in the same file, another Python module, or a package within your project’s file system. A function called within a function is called an inner function.

Let’s see in detail how to call functions within functions in Python. To achieve this, we will cover a function calling another function from

  1. from the same file
  2. from another file or a module
  3. from a module in a package or sub-package

How to call a function from the same Python file within a function

The simplest way to call a function within a function is from the same file. It is simple because you do not need to import (from module import function). The function is already declared in the same file; thus, you only need to call it.

Thus, functions you define at the top of your Python code in the same file can be defined inside other functions that come down the line. These functions you define inside other functions are called nested or inner functions.

Let’s say you have two functions, walk() and talk(), within the same Python file.

def talk():
    return "Talking"


def walk():
    return "Walking"

These two functions can call each other whenever it makes sense. For example, the function walk() can call the function talk() to use its functionality in its code.

You can call the talk() function within the walk() function to show a human being can walk while still talking. Here’s how you would call the function with the walk() function.

Create a Python .py file in a new directory anywhere in your file system. I will create a new directory, python, within my Desktop folder.

mkdir ~/Desktop/python

Navigate into the directory

cd ~/Desktop/python

Create a file inside the new directory. Name it main.py or whatever name you may want.

touch main.py

Open the folder using your favorite IDE or code editor

code .

Insert the following code

def walk(locomotion=True, is_talking=False):
    # assume the person is talking
    is_talking = True
    
    # if they are talking
    if is_talking:
        talking = talk()
        return f"Walking while {talking}"
    
    # if not talking, just return a quiet walk
    return "Walking"

So, whenever we invoke the walk() function, we assume that the person is also talking by setting the variable is_talking to True. So, the walk() function should invoke the talk() function within it and return “Person was walking while talking.”

print(f'Muthoni was {walk()}')

Results:

Muthoni was Walking while Talking

See how easy that was. We have called a function within a function to implement a solution that makes sense.

Now, what if the functions walk() and talk() were in their own separate file? How can we call the function talk() within the walk() function?

How can a function call another function from another Python module

You can call another function from a separate Python module within a function using the import module function or from module import function statements.

Place the talk() function in a separate Python module (.py file) in the same directory as your main.py file. So, you have to create another file called maybe talk_module.py or anything.

touch talk_module.py

Cut all the talk() function code from the main.py file and place it inside the new file, talk_module.py.


def talk():
    return "Talking"

Return to the main.py file, and your editor should show some errors, or when you try to run the code, it won’t work.

To resolve the “NameError: name ‘talk’ is not defined,” and use the function within our talk() function, we must import it from the new module we created.

Add the following code at the top of your main.py file

from talk_module import talk

Your final main.py file should look like this:

from talk_module import talk


def walk(locomotion=True, is_talking=False):
    # assume the person is talking
    is_talking = True
    
    # if they are talking
    if is_talking:
        talking = talk()
        return f"Walking while {talking}"
    
    # if not talking, just return a quiet walk
    return "Walking"


print(f'Muthoni was {walk()}')

If you run your code, it should now work.

Muthoni was Walking while Talking

That’s how you can call a function from another Python module within a function in Python.

Let’s now see how you can do the same thing while using a package.

How to call a function from a package or sub-package within a function

Suppose you have a separate directory that you want to use its modules within a new function. In that case, you can import the modules and their functionality directly or create __init__.py file to turn the directory into a package.

How to import a function directly from a Python module in a separate directory

You can import a function directly from a module in a separate directory by referencing its path using the following syntax: from directory.module import function to import a particular function or from directory.module import * to import all the functionality within the module.

For example, create a new directory within the current working directory with the file main.py. Name it talk_package or any name.

mkdir talk_package

Move our talk_module.py file inside the new directory.

mv talk_module.py ./talk_package

If you run our main.py file, it will not execute because Python cannot find the module’s location, talk_module.py. To resolve the NameError, you need to instruct the Python interpreter on the new location of the file by using from directory.module import function or from directory.module import *

from talk_package.talk_module import talk

So, your final main.py file should look like this:

from talk_package.talk_module import talk


def walk(locomotion=True, is_talking=False):
    # assume the person is talking
    is_talking = True
    
    # if they are talking
    if is_talking:
        talking = talk()
        return f"Walking while {talking}"
    
    # if not talking, just return a quiet walk
    return "Walking"


print(f'Muthoni was {walk()}')

After running main.py, voila!

Muthoni was Walking while Talking

Alternatively, you may create __init__.py to instruct Python to recognize the directory as a package.

How to import a function from a package and use it within a function in Python

After creating __init__.py file inside a directory, the Python interpreter can recognize the directory as a package. Thus, you can import modules and their functionality within them by using from talk_package import * or from package.module import *

Here’s how to turn a directory into a package in Python.

Create a new file inside the talk_package directory and name it __init__.py

touch talk_package/__init__.py

Add the following code to the file to instruct Python to load the module declared inside the __all__ variable.

echo "__all__ = ['talk_module']" > talk_package/__init__.py 

Adjust your main.py file by changing the import statement at the top to reflect the following:

from talk_package import *

Now, you can use all the functionality of the modules defined inside the __init__.py file.

For example, you can use module.function() syntax in your main.py file.

from talk_package import *


def walk(locomotion=True, is_talking=False):
    # assume the person is talking
    is_talking = True
    
    # if they are talking
    if is_talking:
        talking = talk_module.talk()
        return f"Walking while {talking}"
    
    # if not talking, just return a quiet walk
    return "Walking"


print(f'Muthoni was {walk()}')

Results:

Muthoni was Walking while Talking

That’s how you can use a function within a function from various locations- within the same file, from a module, and a package. Follow this link to learn more about Python functions in Python.

Related Questions

Can you call a function within an f-string in Python?

You can call a function within an f-string in Python. Python f-string syntax allows you to call a function or functions within it. Here is an example of two functions being called within an f-string statement: f”Muthoni was {walk()}ing while {talk()}ing”

Conclusion

Whenever you create a function in Python, it qualifies to be called by another function within your program. Besides, you can separate functionality within your code across multiple files and still use these functions from separate files within a function.

When you achieve that, you write an elegant, maintainable code that breaks a problem into multi sub-problems that can be solved effectively.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *