Skip to content

Latest commit

 

History

History
45 lines (39 loc) · 730 Bytes

File metadata and controls

45 lines (39 loc) · 730 Bytes

Lambdas, Closures, Decorators, Docstrings, Mutable Defaults

Lambda Functions

add = lambda x, y: x + y

Closures

def outer(x):
    def inner(y):
        return x + y
    return inner

Decorators

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('Before')
        result = func(*args, **kwargs)
        print('After')
        return result
    return wrapper

@my_decorator
def greet():
    print('Hello!')

Docstrings & Type Hints

def foo(a: int) -> int:
    """Adds 1 to a"""
    return a + 1

Mutable Default Args (Edge Case)

def f(a=[]):
    a.append(1)
    return a
print(f())  # [1]
print(f())  # [1, 1] <-- Beware!