Python execute function in function

Python Nested Functions

Functions are one of the «first-class citizens» of Python, which means that functions are at the same level as other Python objects like integers, strings, modules, etc. They can be created and destroyed dynamically, passed to other functions, returned as values, etc.

Python supports the concept of a «nested function» or «inner function», which is simply a function defined inside another function. In the rest of the article, we will use the word «inner function» and «nested function» interchangeably.

There are various reasons as to why one would like to create a function inside another function. The inner function is able to access the variables within the enclosing scope. In this article, we will be exploring various aspects of inner functions in Python.

Defining an Inner Function

To define an inner function in Python, we simply create a function inside another function using the Python’s def keyword. Here is an example:

def function1(): # outer function print ("Hello from outer function") def function2(): # inner function print ("Hello from inner function") function2() function1() 
Hello from outer function Hello from inner function 

In the above example, function2() has been defined inside function1() , making it an inner function. To call function2() , we must first call function1() . The function1() will then go ahead and call function2() as it has been defined inside it.

It is important to mention that the outer function has to be called in order for the inner function to execute. If the outer function is not called, the inner function will never execute. To demonstrate this, modify the above code to the following and run it:

def function1(): # outer function print ("Hello from outer function") def function2(): # inner function print ("Hello from inner function") function2() 

The code will return nothing when executed!

def num1(x): def num2(y): return x * y return num2 res = num1(10) print(res(5)) 

The code returns the multiplication of the two numbers, that is, 10 and 5. The example shows that an inner function is able to access variables accessible in the outer function.

So far, you have seen that it is possible for us to access the variables of the outer function inside the inner function. What if we attempt to change the variables of the outer function from inside the inner function? Let us see what happens:

def function1(): # outer function x = 2 # A variable defined within the outer function def function2(a): # inner function # Let's define a new variable within the inner function # rather than changing the value of x of the outer function x = 6 print (a+x) print (x) # to display the value of x of the outer function function2(3) function1() 

The output shows that it is possible for us to display the value of a variable defined within the outer function from the inner function, but not change it. The statement x = 6 helped us create a new variable x inside the inner function function2() rather than changing the value of variable x defined in the outer function function1() .

Читайте также:  Php for sql injection

In the next section, we will be discussing the main reasons as to why we use inner functions in Python.

Why use Inner Functions?

Encapsulation

A function can be created as an inner function in order to protect it from everything that is happening outside of the function. In that case, the function will be hidden from the global scope. Here is an example:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

def outer_function(x): # Hidden from the outer code def inner_increment(x): return x + 2 y = inner_increment(x) print(x, y) inner_increment(5) #outer_function(5) 
Traceback (most recent call last): File "C:/Users/admin/inner.py", line 7, in inner_increment(5) NameError: name 'inner_increment' is not defined 

In the above code, we are trying to call the inner_increment() function, but instead we got an error.

Now, comment out the call to inner_increment() and uncomment the call to outer_function() as shown below:

def outer_function(x): # Hidden from the outer code def inner_increment(x): return x + 2 y = inner_increment(x) print(x, y) #inner_increment(5) outer_function(5) 

The script above shows that the inner function, that is, inner_increment() is protected from what is happening outside it since the variable x inside the inner_increment function is not affected by the value passed to the parameter x of the outer function. In other words, the variables inside the inner function is not accessible outside it. There is a great advantage with such a design pattern. After checking all arguments in the outer function, we can safely skip error checking within the inner function.

Closures and Factory Functions

All the examples we have seen till now just contain ordinary functions that have been nested inside other functions. It is possible for us to write such functions in another way instead of nesting them inside other functions. We don’t have a specific reason as to why we should nest them.

However, for the case of closures, one must use the nested functions.

We can bind/pass data to a function without necessarily passing the data to the function via parameters. This is done using a closure. It is a function object that is able to remember values in the enclosing scopes even when they are not available in the memory. This means that we have a closure when a nested function references a value that is in its enclosing scope.

The purpose of a closure is to make the inner function remember the state of its environment when it is called, even if it is not in the memory. A closure is caused by an inner function, but it’s not the inner function. The closure works by closing the local variable on the stack, which stays around after the creation of the stack has finished executing.

Читайте также:  React code in html

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

  • There must be a nested function
  • The inner function has to refer to a value that is defined in the enclosing scope
  • The enclosing function has to return the nested function

Consider the following example:

def function1(name): def function2(): print('Hello ' + name) return function2 func = function1('Nicholas') func() 

The above code demonstrates that with closures, we are able to generate and invoke a function from outside its scope via function passing. The scope of function2() is only inside function1() . However, with the use of closures, it was possible for us to extend this scope and invoke it from outside its scope.

Inner functions help us in defining factory functions. A factory function is a function that creates another object. For example:

def power_generator(num): # Create the inner function def power_n(power): return num ** power return power_n power_two = power_generator(2) power_three = power_generator(3) print(power_two(8)) print(power_three(4)) 

In the script above, from the power_n(power) function, we have created two other objects, power_two and power_three . This makes power_n(power) a factory function since it generates the power_two and power_three functions for us using the parameter we pass it.

Conclusion

An inner function is simply a function that is defined inside another function. The inner function is able to access the variables that have been defined within the scope of the outer function, but it cannot change them. There are a number of reasons as to why we may need to create an inner function. For instance, an inner function is protected from what happens outside it. Inner functions are also a good way of creating closures in Python.

Источник

Call Function from Another Function in Python

To call a function, we have to define that function using the def keyword, so we used that to define the test() function. Then, inside the test() function, we used the print() function to print a message, which would be printed on the execution of this function.

In function calls, we have two terms; Calling Function and Called Function . Here, the Calling Function is the function which invokes another function while the Called Function is the function which is being invoked.

Now, you may have a question about how the function execution works. How to decide where to return, particularly in the nested function call, which we will learn in the next section? The stack, the first-in-last-out data structure, handles function calls. How? Let’s see the following.

Читайте также:  New type class python

Call function in Python

In the above diagram, we had a function test() ; when we called it, it was pushed to the stack to hold the reference to know where to return. Then, it executed the test() function and returned.

After that, the function was popped from the stack and returned to a point where it left the program execution and continued.

Now, you might be wondering why to struggle with all these and write functions; it is because the functions serve us with the following features:

  • It avoids code repetition, encourages code reusability and thus saves time, money, and memory.
  • It assists in hiding the code and lets us understand the modules efficiently.
  • Functions help us to break down big problems into smaller modules.
  • Functions can only be defined using the def keyword and a colon followed by a function name.
  • The statements of a function can only be executed with the function name.

You can read this to see what characters are allowed while writing the name of the function in Python. Now, assume we have a situation where we have to call a function from another. The concept would be the same, and a stack data structure would be used. Let’s see how?

Call Function from Another Function in Python

To call function from another function in Python:

  • Write a function_A() function, which prints a message and returns.
  • Write another function_B() function which prints a message, calls function_A() that we created in the previous step and returns.
  • Now, call function_B() function.

Here, we wrote two functions, function_A() and function_B() , both had one print statement to print a message, but we also called function_A() from function_B() .

Nothing happened until we reached the statement, where called function_B as function_B() . As soon as we called function_B() , it was pushed to the stack, and the execution of the function_B started. It printed the statement I am function B. and called function_A as function_A() .

Now, the function_A is also pushed to stack and execution of function_A started; we got another statement printed on the console as I am function A. . Once we are done with function_A , it would be popped from the stack and returned where we left the function_B .

As we can see in the above code, we had a return statement after calling function_A , so the function_B also popped from the stack and returned where we left the program after calling the function_B .

So now, we only have one print statement to be executed, which printed I am now outside the functions. on the console. At this point, we had three statements printed on the console and the stack was also empty.

Let’s visualize the execution of the above program in the following diagram.

Call function from another function in Python

We can also call one function from another within the same and different classes. Let’s learn it below.

Источник

Оцените статью