Asbestos Supply

2022-06-08 Python Notes

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 by def
  • Use : after the beginning of the code block, e.g. def foo(arg1):

Dictionaries

  • calling .keys(), .values(), .items() returns a dict_keys, dict_values, and dict_items type respectively.
    • wrap in list() function to get a list that can be sorted, etc: list({"foo":1, "bar":2}.keys())

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 like deconst(1, 2)
    • and def deconst(**kwargs:)... can be called like deconst(foo=1, bar=2) or deconst({"foo":1, "bar":2})
  • 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 js import x from y or const x = require(y)

Classes

  • constructor becomes __init__ and takes an argument self, 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