Multilingual content from IBKR

Close Navigation
Learn more about IBKR accounts
Python Function Tutorial – Part IX

Python Function Tutorial – Part IX

Posted June 5, 2020 at 3:14 pm
Jay Parmar

See the previous installment in this series, DocStrings, to get up-to-date in this tutorial.

Nested Python functions and non-local variable

A nested Python function is a function that is defined inside another function. The syntax for the nested function is the same as that of any other Python function. Though the applications of nested functions are complex in nature and limited at times, even in the quant domain, it is worth mentioning, as we might encounter this out there in the wild. Below is an example which demonstrates the nested Python functions.

# Defining nested function
def outer():
“”” This is an enclosing function “””
def inner():
“”” This is a nested function “””
print(‘Got printed from the nested function.’)
print(‘Got printed from the outer function.’)

We define the Python function outer which nests another Python function inner within it. The outer function is referred to as an enclosing function and inner is known as nested function. They are also referred to as inner functions sometimes. Upon calling the outer function, Python will, in turn, call the inner function nested inside it and execute it. The output for the same is shown below:

# Calling the ‘outer’ function
# Output
Got printed from the outer function.
Got printed from the nested function.

The output we got here is intuitive. First, the print statement within the outer function got executed, followed by the print statement in the inner function. Additionally, nested functions can access variables of the enclosing functions. i.e. variables defined in the outer function can be accessed by the inner function. However, the inner or the nested Python function cannot modify the variables defined in the outer or enclosing Python function.

def outer(n):
number = n
def inner():
print(‘Number =’, number)

A call to outer function will print the following

# Output
Number = 5

Though the variable number is not defined within inner function, it is able to access and print the number. This is possible because of scope mechanism that Python provided. We discuss more on this in the following section. Now consider, what if we want the nested Python function to modify the variable that is declared in the enclosing Python function. The default behavior of Python does not allow this. If we try to modify it, we will be presented with an error. To handle such a situation, the keyword nonlocal comes to the rescue.

In the nested Python function, we use the keyword nonlocal to create and change the variables defined in the enclosing Python function. In the example that follows, we alter the value of the variable number.

def outer(n):
number = n
def inner():
nonlocal number
number = number ** 2
print(‘Square of number =’, number)
print(‘Number =’, number)
print(‘Number =’, number)

A call to the outer Python function will now print the number passed as an argument to it, the square of it and the newly updated number (which is nothing but the squared number only).

# Output
Number = 3
Square of number = 9
Number = 9

Remember, assigning a value to a variable will only create or change the variable within a particular Python function (or a scope) unless they are declared using the nonlocal statement.

In the next installment, the author will provide code for Variable Namespace and Scope.

Visit for ready-to-use Python functions as applied in trading and data analysis.

Disclosure: Interactive Brokers

Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from QuantInsti and is being posted with its permission. The views expressed in this material are solely those of the author and/or QuantInsti and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.