Over the last number of years I've been predominantly writing code in Typescript and Javascript. I'm starting a new position that requires using Python. My prior experience with Python was all one-off scripts and so I'm excited to learn it. I decided to keep some notes here. These are intended mostly reminders for myself and I imagine will mostly focus on how Python is different than JS/TS. But maybe it'll help someone too...
Code Blocks
- Use indentation instead of brackets
function
is replaced bydef
- Use
:
after the beginning of the code block, e.g.def foo(arg1):
Dictionaries
- calling
.keys()
,.values()
,.items()
returns adict_keys
,dict_values
, anddict_items
type respectively.- wrap in
list()
function to get a list that can be sorted, etc:list({"foo":1, "bar":2}.keys())
- wrap in
Lists
.sort()
is stable
Functions
- You can define unknown arguments using
*args
(for just values) or**kwargs
(for key/val)- e.g.
def deconst(*args):...
can be called likedeconst(1, 2)
- and
def deconst(**kwargs:)...
can be called likedeconst(foo=1, bar=2)
ordeconst({"foo":1, "bar":2})
- e.g.
- Functions are first-class and can be passed around (like JS). Decorators are used to wrap functions
- decorator functions take a function as a param and return a function that wraps it
- the
@
symbol is used to decorate a function (e.g.@some_decorator
is prepended to the function to decorate - then calling the function will actually call the wrapped function returned by the decorator
- use
*args
(and**kwargs
) in the function returned by the decorator to create a reusable decorator that takes (and passes) any number of parameters - when writing function decorators, make sure to
import functools
and call@functools.wraps(func_arg)
inside the decorator. This ensures that attributes like__name__
are updated for introspection (reflection) purposes - decorators can be used on classes too and there's a bunch of built in decorators for creating static methods and getter/setters. realpython has a great writeup
Imports
- use
from y import x
instead of the jsimport x from y
orconst x = require(y)
Classes
constructor
becomes__init__
and takes an argumentself
, i.e.def __init__(self):
Strings
f-strings
provide interpolation using regular brackets:print(f"1 + 1 = {1+1}")
- you can output the name of the variable and its value by just appending an equal sign:
print(f"{foo = }")
- it also supports fills and formatting. some good details here
- you can output the name of the variable and its value by just appending an equal sign: