Can i call a nested function python?

Hello Learners, today we will learn how to call a nested function in Python with this small tutorial.

Just like nested loops or conditions, nested functions are nothing but function within a function i.e. a function defined inside another function.

Python supports First-Class Function which means python treats the functions as objects. You can pass functions as an argument, return them or you can save them in data structures also. You can do it using Python Closures i.e. a function instance enclosed within an enclosing scope.

There is one thing you should take care of, you must have to call the outer function to call the inner function because it’s scope is inside that function.

So without wasting the time let’s jump into the code snippet so you can have a better understanding of the concept.

def func(x):
    print('hello')
    print("{} is of type {}".format(x,(type(x))))
    
    def nested(x):
        print('inside nested function')
        x=int(x)
        print("{} is of type {}".format(x,(type(x))))
    nested(x)
  
func('2')

OUTPUT:

hello
2 is of type <class 'str'>
inside nested function 
2 is of type <class 'int'>

In this code snippet, on calling function func() with value 2 of string type, it starts executing.

On line 9 it calls the nested function within the func() function and then the nested function is executed.

So in this manner, the nested function is called every time we call the func() function automatically because it is called inside the func() function.

The Requirement of Nested Functions: nested function call

Python Closures or you can say nested function objects can be used to protect or filter some functionalities inside that function. These functionalities are protected from outer space or processes which is nothing but Encapsulation. It can be achieved by using nested functions.

Now suppose you don’t want to execute the nested() function all the times you call func(), what will you do now?

def func(x):
    print('hello')
    print("{} is of type {}".format(x,(type(x))))
    
    def nested(x):
        x=int(x)
        print("inner function : {} is of type {}".format(x,(type(x))))
    
    print("{} is of type {}".format(x,(type(x))))
    return nested

f = func('2')
f('2')

OUTPUT: 

hello
2 is of type <class 'str'>
2 is of type <class 'str'>
inner function : 2 is of type <class 'int'>

In this code snippet, the outer function is called on line 12 but the inner function is not. It will be called only when we call this new function named ‘f’  with specified arguments.

On line 13, we called f with the parameter required and we can see the output. The inner function is called and the argument is converted into an integer.

There is another concept of nonlocal keyword which we’ll learn in another tutorial when we’ll discuss the scope of variables. For now, you can see this article for the nonlocal keyword.

Can i call a nested function python?

A nested function is simply a function within another function, and is sometimes called an "inner function". There are many reasons why you would want to use nested functions, and we'll go over the most common in this article.

How to define a nested function

To define a nested function, just initialize another function within a function by using the def keyword:

def greeting(first, last):
  # nested helper function
  def getFullName():
    return first + " " + last

  print("Hi, " + getFullName() + "!")

greeting('Quincy', 'Larson')

Output:

Hi, Quincy Larson!

As you can see, the nested getFullName function has access to the outer greeting function's parameters, first and last. This is a common use case for nested functions–to serve as small helper function to a more complex outer function.

Reasons to use nested functions

While there are many valid reasons to use nested functions, among the most common are encapsulation and closures / factory functions.

Data encapsulation

There are times when you want to prevent a function or the data it has access to from being accessed from other parts of your code, so you can encapsulate it within another function.

When you nest a function like this, it's hidden from the global scope. Because of this behavior, data encapsulation is sometimes referred to as data hiding or data privacy. For example:

def outer():
  print("I'm the outer function.")
  def inner():
    print("And I'm the inner function.")
  inner()

inner()

Output:

Traceback (most recent call last):
  File "main.py", line 16, in <module>
    inner()
NameError: name 'inner' is not defined

In the code above, the inner function is only available from within the function outer. If you try to call inner from outside the function, you'll get the error above.

Instead, you must call the outer function like so:

def outer():
  print("I'm the outer function.")
  def inner():
    print("And I'm the inner function.")
  inner()

outer()

Output:

I'm the outer function.
And I'm the inner function.

Closures

But what would happen if the outer function returns the inner function itself, rather than calling it like in the example above? In that case you would have what's known as a closure.

The following are the conditions that are required to be met in order to create a closure in Python:

These are the conditions you need to create a closure in Python:

1. There must be a nested function

2. The inner function has to refer to a value that is defined in the enclosing scope

3. The enclosing function has to return the nested function

- Source: https://stackabuse.com/python-nested-functions/

Here's a simple example of a closure:

def num1(x):
  def num2(y):
    return x + y
  return num2

print(num1(10)(5))

Output:

15

Closures make it possible to pass data to inner functions without first passing them to outer functions with parameters like the greeting example at the beginning of the article. They also make it possible to invoke the inner function from outside of the encapsulating outer function. All this with the benefit of data encapsulation / hiding mentioned before.

Now that you understand how and why to nest functions in Python, go out and nest 'em with the best of 'em.


Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Can you call a nested function?

Generally defining a function inside another function is to scope it to that function and you can't call a nested function in JavaScript. You have to do something inside in outer funciton to make inner funciton available outside it. You will need to return the inner function call.

Can you call a nested function outside a function?

Nested function is private to containing function Only the containing function can access the nested function. We cannot access it anywhere outside the function. This is because the inner function is defined in the scope of the outer function (or containing function).

Can you call a function within another function Python?

In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems.

Are nested functions allowed in Python?

If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.