Advanced Python (Fall 2017)/lecture4

From ICO wiki
Jump to navigationJump to search

Lecture 4: Functional Programming

See this for a more detailed document on functional programming in python

Functions as first class objects

function in python are first class objects.

They can be assigned to variable, passed into other function as arguments, and be returned by a function.

Python is not optimal for functional programming.

Currying in python. And an equivalently functioning block of code written using a class.

def my_function(name):
    def inside_function():
        print('hi {}'.format(name))
    return inside_function

a1 = my_function('bob')
a2 = my_function('sally')

a1()  # 'hi bob'
a2()  # 'hi sally'

class MyClass():
    def __init__(self, name): = name

    def __call__(self):
        print('hi {}'.format(

my_instance = MyClass('Alex')
my_instance()  # 'hi Alex'


Here is a more detailed tutorial for decorators:

decorators can wrap a function and make the function do something different, or use the function in a different context. You most likely will not have to write your own decorators in your scripts and applications. But you may likely use one from a library.

def my_decorator(f):
    def wrapped():
        print('Decorator Engaged!')
    return wrapped

def decorated_hello_world():
    print('hello world')



Lambdas are similar to functions. Here are two equivalent lines of code. Lambdas should not have side effects. They should be anonymous, meaning that they do should not be assigned to a name. They should be used as an argument to a function call.

# Do not name a lambda. Define a function instead.
my_lambda = lambda x, y: x + y

def my_function(x, y):
    return x + y

Using Lambdas, map, comprehensions