Python quick note

Anh-Thi Dinh
draft
⚠️
This is a quick & dirty draft, for me only!
Miscellaneous
  • ; is not used, use spaces instead!
  • If you wanna 2 or more commands in 1 line, you can use ; to separate them.
  • Tab size usually is 4.
  • Lines can be broken with just an Enter, you also use \\ between the lines if you want.
  • From Python 3.6, you can use 1_000_000 for the number 1000000.
  • from __future__ import <package> allows current version of python to use <package> which is only available in the "future" version of python.
  • if __name__ == "__main__": determines the main running file of codes. The codes inside this command only run if the file containing it is the main executed file! (read more)
  • If we don't need to mention some variable, use _:
    • 1for _ in range(2):
      2  print("Thi")
      1Thi
      2Thi
Python scripts and locations
1my_project/
2├── scripts/
3   ├── __init__.py
4	 ├── helpers.py
5   └── my_script.py
A special case, my_script.py is in the same folder with helpers.py
1# run
2python -m scripts.my_script # without .py
1# my_script.py
2from .helpers import ...
3
4if __name__ == "__main__":
5    main()
Logging
The order from DEBUG < INFO < WARNING < ERROR < CRITICAL (lowest to highest severity)
1import logging
2import os
3from dotenv import load_dotenv
4
5load_dotenv()
6
7def configure_logging():
8    env = os.getenv("ENV_NAME", "prod")
9    logging.basicConfig(
10		    # show logs from DEBUG when ENV_NAME is 'dev', otherwise from INFO
11        level=logging.DEBUG if env == 'dev' else logging.INFO,
12        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
13        datefmt='%y-%m-%d %H:%M' # 24-01-23
14    )
15    
16configure_logging()
17
18# usage
19logging.debug('something')
If there is error “TypeError: not all arguments converted during string formatting
1# error
2logging.info("x: ", x)
3
4# fixed
5logging.info(f"x: {x}")
Swap 2 variables
1a, b = b, a
Clear variables
1# Clear (without confirmation) a variable from workspace
2del <var>
3%reset_selective <var>
1# Check if available and then delete
2if '<var>' in globals(): del <var>
3# use locals() inside a def
1# Clear all variables
2%reset # with confirmation
3%reset -f # without confirmation
Auto remove unused imports
  • Install packages
    • 1pip install autoflake isort
  • Make autoflake be default formatter (VSCode’s setting json file)
    • 1{
      2	"[python]": {
      3	  "editor.defaultFormatter": "mikoz.autoflake-extension"
      4	}
      5}
Flask vs fastapi : r/flask , django for building web apps.
  • Flask is easier than FastAPI. Flask is “do whatever you want”, good when you need both back and front into one package.
  • as things get bigger, with more endpoints, more base routes (the http://website.com/<ROUTE>/other/stuff part), FastAPI has made my life quite nice.
  • FastAPI so when speed is important as well as organization, models, validation, and you do want things like async
different parts of your program run concurrently and can simplify your design
1import threading
2x = threading.Thread(target=thread_function, args=(1,))
3x.start()
  • Most Python 3 implementations the different threads do not actually execute at the same time: they merely appear to
  • Tasks that spend much of their time waiting for external events are generally good candidates for threading.
If you define a new funciton and wait for it plementation, just use pass as its content.
1def somefunction():
2	pass
Using d.get("prop", default_value) for dictionary in Python. .get() always returns a value whereas d["prop"] will raise a KeyError if the given key is missing.