Skip to content

Python

TODOs

Functions

Forced name params

  • pass a * to separate positional args and keyword args
def foo(pos, *, forcenamed, **kwargs):
    pass

my_func(1, 2) # throws an error

Mark a function as deprecated

Trivia

def yell():
    pass

bark = yell

del yell  # only deletes one pointer to the function

bark()  # still in the heap because there's still one pointer left

CLI

-m flag: Module

python -m module_name args

  • run a module
  • python -m http.server
    • start http server on port 8000 in current directory
  • python -m pdb path/to/file.py
    • debug a Python script
  • python -m pip install ...
    • guarantee that you're running the version of pip that's connected to the current python

-i flag: Interactive

Debug the state of a broken Python code when it crashed!

Although you should use breakpoint() and pdb

$ python3 -i add.py 4 7
Traceback (most recent call last):
  File "/home/trey/add.py", line 5, in <module>
    print(sum(numbers))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

# can debug to see the state of the program when it crashed!
>>> __name__
'__main__'
>>> sys.argv
['add.py', '4', '7']
>>> numbers
['4', '7']

File system

Path

from pathlib import Path

file_directory = Path(__file__).parent.resolve()
another_path = file_directory / "sql_scripts"

Get an environment variable value

os.environ.get('ENV_VAR_NAME', 'FALLBACK_VALUE')

os.getenv() is an alias to os.environ.get()

Equality

== vs is

  • is: same ID
    • place in the stack/heap
    • id(x) => 140079600030400
  • ==: uses __eq__
    • by default, == delegates to is

isinstance vs type()

  • type: returns the name of the type
  • isinstance([1,2,3], list)
    • goes up the inheritance tree
    • can catch more than comparing two types

walrus operator

match = MY_REGEX.search(string)
if match:
    pass
if match := MY_REGEX.search(string):
    pass
while chunk := f.read(8192):
    md5.update(chunk)
  • new in Python 3.8
  • assignment expression
    • merge two lines into one
  • assignment statements needs to be on their own line
  • When to use?
    • only if it makes your code more readable

Random

Pseudorandom

import random
>>> colors = ['blue', 'purple', 'green', 'yellow']
>>> random.choice(colors)
'purple'

Closer to true random

import secrets
secrets.choice(colors)

Last update: 2023-04-24