Functions are objects
Higher order functions take functions as inputs
def fun(f, x):
return f(x)
Functions that take other functions as arguments
def decorator(f):
def wrapper(*args, **kwargs):
...
f()
...
return wrapper
@decorator
def funct():
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
You can use decorators inside of classes, on methods
class MyClass:
@method_decorator
def class_method(self):
You can actually decorate entire classes!
@dec
class ClassName:
You can apply multiple decorators to the same function
@dec2
@dec1
def f:
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
Positional-only
Keyword-only
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])
def f(x, *t, **d):
f(1, 2, 3, person = 'tom', rival = 'sue')
They produce iterators
Each time the function is called, it
yield
keyword)
yield, it
returns the new state and pausesdef fibonnaci():
x,y = 0, 1
while True:
yield x + y
x, y = y, x+ y
Saves memory since it generates on-the-fly
Chain generators to process data in stages efficiently
Create arbitrarily long sequences
send()
close
The same as list comprehension, but use parentheses
sq = (x*x for x in range(1,6))