| Basic function |
const book = {title: "Dune", author: "herbert"}
function describe(book) {
return `${book.title} is good`;
}
console.log(describe({ title: "Dune" }));
|
`def` instead of `function`, a colon + indentation instead of braces.book = {"title": "Dune", "author: "Herbert"}
def describe(book):
return f"{book['title']} is good"
print(describe({"title": "Dune"}))
|
| Order of Arguments |
Arguments print in the same order as they were passed infunction printFn(a, b, c) {
console.log(a, b, c);
}
printFn(1, 2, 3);
|
the non positional * vs the positional /# Anything AFTER * must be passed by name, not position.
def print_fn(a, *, b, c):
print(a, b, c)
print_fn(1, b=3, c=2)
# The / separator forces positional-only.
def positional(a, b, /):
print(a, b)
positional(1, 2)
|
| Arrow and Lambda functions |
Arrow functionconst square = (x) => x * x;
console.log(square(5)); // 25
|
Lambda functionssquare = lambda x: x * x
print(square(5)) # 25
|
| Closures |
the inner fn remembers outer statefunction make() {
let borrowed = 0;
return function borrow() {
borrowed += 1; // knows about `borrowed`
return borrowed;
};
}
|
need `nonlocal` to REASSIGN an outer variabledef make():
borrowed = 0
def borrow():
nonlocal borrowed # without this: UnboundLocalError
borrowed += 1
return borrowed
return borrow
|
| Decorators |
no Decorators |
Decoratorsdef log(fn):
def wrapper(*args, **kwargs):
print("starting the function")
result = fn(*args, **kwargs)
print("function executed: {result}")
return result
return wrapper
@log # <-- readable wrapping
def print_title(title):
return f"I need to print {title}"
print(print_title("Python for JS Devs"))
|