Course Content
Mastering Python: Closures and Decorators
Mastering Python: Closures and Decorators
Closure with Arguments
There are different ways to use arguments in closure:
- Argument for the outer function.
- Argument for the inner function.
Outer Argument
Arguments for the outer function is used to enclose the values inside the function exactly once. This works like initialization:
def start_count(start=1, step=1): counter = start def inner(): nonlocal counter result = counter counter += step return result return inner first_counter = start_count() second_counter = start_count(13, 14) print("First counter:") print(first_counter()) print(first_counter()) print("Second counter:") print(second_counter()) print(second_counter()) print("First counter:") print(first_counter()) print(first_counter()) print("Second counter:") print(second_counter()) print(second_counter())
The example above implements a counter function. The start_count()
function takes two arguments: start
and step
, with default values of 1
. The start
value is assigned to the variable counter
. The counter
and step
are then used inside the inner()
function.
The arguments' values start
(counter
) and step
are enclosed in the inner() function as parameters for the counter.
The variables first_counter
and second_counter
contain the inner()
functions with enclosed parameters. These variables are functions that can be called without parameters.
Note
The variables
first_counter
andsecond_counter
are independent counters: as an example, we can see how each of them has its own separate value and performs certain actions.
Inner Arguments
The inner()
function is a returned function assigned to variables. The arguments that the inner()
takes are used every time the inner()
function is called via variables.
def hero_hit(hero_name="Unknown"): def inner(monster="Unknown"): print("The", hero_name, "hero hit the", monster, "monster") return inner john = hero_hit("John") # use the outer argument john("Goblin") # use the inner argument john("Dinosaur") # inner("Goblin") john() # inner() john("Dragon") # inner("Dragon")
Arguments passed to the inner()
function behave like regular function arguments and are not related to the closure.
Thanks for your feedback!