Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

DCIT 23: Computer Programming 2

More About Functions


Function Objects, Closure, LEGB, Lambda

Russel L. Villacarlos
College of Engineering and Instructor / Professor
Information Technology
Function Objects
def greet(greeting, person):
print(greeting, person)
• Functions (and methods) in
def make_repeating(step, fn):
Python are objects def repeating_fn(*args):
for i in range(step):
fn(*args)
• The def function_name() return repeating_fn
statement creates a
greeting_func = greet
function object and assign
it to a variable named #Outputs <class 'function'>
print(type(greet))
function_name print(type(greeting_func))

greeting_func('Hello World', 'Russel')

greeting10x = make_repeating(10, greet)


College of Engineering and greeting10x('Hi', 'Russel')
Information Technology
Function Objects
def greet(greeting, person):
print(greeting, person)
• A function is a first-class
def make_repeating(step, fn):
object def repeating_fn(*args):
• It has a type for i in range(step):
fn(*args)
• It can be assigned to a
variable or stored in a return repeating_fn
collection like lists, sets, or greeting_func = greet
map
• It can be passed as #Outputs <class 'function'>
print(type(greet))
argument of another function print(type(greeting_func))
• It can be returned by
greeting_func('Hello World', 'Russel')
another function
greeting10x = make_repeating(10, greet)
College of Engineering and greeting10x('Hi', 'Russel')
Information Technology
Nested Function
def greet(greeting, person):
print(greeting, person)
• A function can also be
created inside another def make_repeating(step, fn):
function to create nested def repeating_fn(*args):
function for i in range(step):
fn(*args)

• A nested function has access return repeating_fn


to variables defined in the
enclosing function greeting_func = greet
• These variables are called #Outputs <class 'function'>
non-local variables print(type(greet))
• Non-local variables are by print(type(greeting_func))
default not modifiable unless
declared using the nonlocal greeting_func('Hello World', 'Russel')
statement inside the nested
function greeting10x = make_repeating(10, greet)
College of Engineering and greeting10x('Hi', 'Russel')
Information Technology
Nested Function

• A function can also be def factorial(n):


created inside another def fact(n,p):
function to create nested if n == 1:
function
return p
return fact(n - 1, n * p)
• A nested function has access
to variables defined in the return fact(n, 1)
enclosing function
• These variables are called print(factorial(10))
non-local variables
• Non-local variables are by
default not modifiable unless
declared using the nonlocal
statement inside the nested
function
College of Engineering and
Information Technology
Nested Function

• A function can also be def fibonacci(n):


created inside another
function to create nested fibs = [0,1]
function def fib(i):
nonlocal fibs
• A nested function has access if i >= len(fibs):
to variables defined in the
enclosing function fibs.append(fib(i - 1) +
• These variables are called fib(i - 2))
non-local variables
• Non-local variables are by return fibs[i]
default not modifiable unless
declared using the nonlocal return fib(n)
statement inside the nested
function
College of Engineering and
Information Technology
Closure
def greet(greeting, person):
print(greeting, person)
• A closure is a nested
def make_repeating(step, fn):
function that retains the def repeating_fn(*args):
nonlocal values even when for i in range(step):
fn(*args)
the enclosing function is
not active return repeating_fn

greeting_func = greet

• Closures created from a #Outputs <class 'function'>


print(type(greet))
single enclosing scope print(type(greeting_func))
have distinct copies of greeting_func('Hello World', 'Russel')
nonlocal values
greeting10x = make_repeating(10, greet)
College of Engineering and greeting10x('Hi', 'Russel')
Information Technology
Closure
def create_fib_like(f0, f1):

• A closure is a nested fibs = [f0,f1]

function that retains the def fib(i):


nonlocal fibs
nonlocal values even when
if i >= len(fibs):
the enclosing function is
fibs.append(fib(i - 1) +
not active
fib(i - 2))
return fibs[i]
• Closures created from a return fib
single enclosing scope f1 = create_fib_like(2,4)
have distinct copies of f2 = create_fib_like(5,7)
nonlocal values
College of Engineering and
Information Technology
LEGB Rule

• When a name is encountered Built-in


during the execution of a Global
program, Python search for
its corresponding object by Enclosing
first looking at the namespace
Local
of the function

a = 1
• This is called the local def outer():
b = 2
namespace def inner():
c = 3
print(a,b,c)
College of Engineering and
Information Technology
LEGB Rule

• If the name is not defined in Built-in


the local namespace, Python Global
will then check the local
namespace of any enclosing Enclosing
function
Local

a = 1
def outer():
b = 2
def inner():
c = 3
print(a,b,c)
College of Engineering and
Information Technology
LEGB Rule

• If none of the enclosing Built-in


functions contains the object, Global
Python will check the
module's namespace Enclosing

Local
• This is called the global
namespace a = 1
def outer():
b = 2
def inner():
• The global namespace c = 3
includes all imported objects print(a,b,c)
College of Engineering and
from Technology
Information other modules
LEGB Rule

• Finally, if the object is not Built-in


found in the global Global
namespace, Python will
check the built-in Enclosing
namespace that includes all
Local
Python built-in functions and
objects
a = 1
def outer():
b = 2
• If this still fails, then Python def inner():
will raise a NameError c = 3
print(a,b,c)
College of Engineering and
Information Technology
LEGB Rule

• The steps taken by Python to Built-in


search for the object that Global
corresponds to a name is
called the LEGB rule Enclosing
• Local
Local
• Enclosing
• Global
• Built-in a = 1
def outer():
b = 2
def inner():
c = 3
print(a,b,c)
College of Engineering and
Information Technology
Lambda

• A lambda function is a function without a name (also called anonymous


function)

• In Python, a lambda function is created using the lambda expression


syntax:
lambda <argument_list>: <expression>

• The lambda expression creates a function object with no associated a


name

• The result of the expression becomes the return value of the lambda
function
• Ex: lambda a,b: a + b
College• ofEx: lambda person:
Engineering and person['name'].upper()
Information Technology
Lambda

• A lambda function in Python is L = [(1,4), (2,3), (0,8), (-1,5)]


meant to be simple and can only
perform a single expression print(sorted(L, key= lambda e:sum(e)))

• They are commonly used in


situation where a def statement is def exp(n):
not allowed
• Ex: A function that is meant to be return lambda x: x**n
passed as argument like a function
to the key argument to the sorted
function
exp2 = exp(2)
• Ex: A simple function to be returned
by another function print(exp2(100))

• Lambda function can also become


College of Engineering and
closures
Information Technology

You might also like