Thi's avatar
HomeAboutNotesBlogTopicsToolsReading
About|My sketches |Cooking |Cafe icon Support Thi
💌 [email protected]

Python quick note

Anh-Thi Dinh
draft
Python
⚠️
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 _:
Python scripts and locations
Logging
The order from DEBUG < INFO < WARNING < ERROR < CRITICAL (lowest to highest severity)
If there is error “TypeError: not all arguments converted during string formatting”
Swap 2 variables
Clear variables
Auto remove unused imports
  • Install packages
  • Install VSCode extension autoflake
  • Make autoflake be default formatter (VSCode’s setting json file)
Flask things
  • Blueprint of Flask, read more this VN article
  • Modular Applications with Blueprints — Flask Documentation (2.3.x)
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
Threading in Python
different parts of your program run concurrently and can simplify your design
  • 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 want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing or concurrent.futures.ProcessPoolExecutor.
If you define a new funciton and wait for it plementation, just use pass as its content.
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.
About|My sketches |Cooking |Cafe icon Support Thi
💌 [email protected]
1for _ in range(2):
2  print("Thi")
1Thi
2Thi
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()
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')
1# error
2logging.info("x: ", x)
3
4# fixed
5logging.info(f"x: {x}")
1a, b = b, a
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
1pip install autoflake isort
1{
2	"[python]": {
3	  "editor.defaultFormatter": "mikoz.autoflake-extension"
4	}
5}
1import threading
2x = threading.Thread(target=thread_function, args=(1,))
3x.start()
threading
1def somefunction():
2	pass