Functions and more on dynamic typing

Introduction

SORT

passing arrays to functions. what is passed? reference ot first? length separately?

Defining functions

Best practice is to name them \(lower\_case\_and\_underscore\).

Everything including functions are objects. As a result functions are first class. Functions can accept functions and can return functions.


def my_function_no_parameters():
    return 0
    
def my_function_with_parameters(x, y):
    return x + y

Decorators

apply @ function to function below to decorate it. syntactic sugar


def my_decorator(func):
    def inner(a):
        print("Printing ", a, " in a decorated way")
        return
    return inner
    
@my_decorator
def just_printing(a):
    print(a)

Default parameters

def f(a: int = 1, b: int = 2) -> int:
    return a + b

Side effects of functions

Can have side effects on objects in parameters if mutable.

Can have side effects on global variables if present.

Passing lists and objects to functions rather than doing literally

def f(a, b):
    return a + b

Can accept multiple variables with *arguments

l=[1,2]
f(*l)

Or can accept named literals with **kwargs (ie key word arguments)

args = {"a":1, "b":2}
f(**args)

Main function in python

def main():
    // Do stuff
if __name__ == "__main__":
    main()

Generators and the yield function

functions which make generators: yield function

Documentation

Function annotations


def my_function(x: "annotation of the input variable x") -> "annotation of the return":
    return x

Type hints

Can but types in annotations. Types are not checked at run time.

def f(a: str, b: str = "apple") -> str:
    return a

Function documentation

defining functions: + triple quote comment at start for documentation


def my_function_no_parameters():
    """
    This is the documentation of my function.
    """
    return 0

Partial functions, Currying and lambda functions

Defining functions using lambdas


my_function = lambda a: a + 1

Closures in Python

Partial functions

from functools import partial

def f(a, b):
    return a + b
    
g = partial(f, 

Currying