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 https://docs.python.org/3/howto/functional.html

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):
        self.name = name

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


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

Decorators

Here is a more detailed tutorial for decorators: https://www.python-course.eu/python3_decorators.php

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!')
        f()
    return wrapped



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


hello_world()

Lambda

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

see https://wiki.itcollege.ee/index.php/I719_Fundamentals_of_Python/lists