python functions

References

Summary

Functions are objects

Higher order functions take functions as inputs

def fun(f, x):
  return f(x)

Decorators

Functions that take other functions as arguments

def decorator(f):
  def wrapper(*args, **kwargs):
     ...
     f()
     ...
  return wrapper

@decorator
def funct():

Use-Cases

Logging: track function calls

Authentication: restrict access in certain circumstances

Rate limiting: control usage per user

Caching: store results

Retry logic: automatically retry failed attempts

Method Decorators

You can use decorators inside of classes, on methods

class MyClass:
  @method_decorator
  def class_method(self):

Class Decorators

You can actually decorate entire classes!

@dec
class ClassName:

Chaining

You can apply multiple decorators to the same function

@dec2
@dec1
def f:  

Default Values

def function(x, y=3):

You can call this with function(1), and it will have x=1, y=3 Or you can overwrite y, with function(1,5)

Note that the default value is only evaluated once

You can pass only specific variables by naming them when you call the function. The naming version is called keywords

def function(x, y=2, z = 5):
...

function(1, z = 7)
def f(pos, /, pos_or_key, *, key):

The symbols / and * are optional and they tell you whether you're allowed to pass in positional or keyword arguments Without those symbols, you can pass everything by position or keyword

Use-cases

Positional-only

Keyword-only

Tuple Arguments

You can set a function to accept arbitrarily many arguments (which will be placed in a tuple)

def f(x,y, *t):

You can actually call a function with a list or tuple, and unpack the sequence

def f(x,y):

f(*[1,2])  

Dictionary Arguments

def f(x, *t, **d):

f(1, 2, 3, person = 'tom', rival = 'sue')  

Lambda Expressions

Annotations

Generator Functions

They produce iterators

Each time the function is called, it

def fibonnaci():
  x,y = 0, 1

  while True:
     yield x + y
     x, y = y, x+ y

Benefits

Saves memory since it generates on-the-fly

Chain generators to process data in stages efficiently

Create arbitrarily long sequences

Methods

send()

close

Generator Expressions

The same as list comprehension, but use parentheses

sq = (x*x for x in range(1,6))