Python
Install
Download and install from python.org
Quick Start
- Install uv
Basics
- Module refers to a .py file.
- Package refers to a folder with init.py along with multiple *.py files.
- A package can have subpackages (which are subfolders with each having their own init.py file)
- Recommended to use absolute imports (imports starting from top level folder/package), instead of relative imports (which is relative to current file)
my_app/
└── src/
└── my_app/
├── __init__.py
├── core/
│ ├── __init__.py
│ └── engine.py
├── utils/
│ ├── __init__.py
│ └── math_utils.py
└── main.py
Async
- Asynchronous execution using async...await
- We cannot use await in top level function. Await can be used only inside an async function.
- Use tasks to start multiple coroutines in parallel and gather to wait on them.
Or with a timeout:
import asyncio async def greet(name, delay): await asyncio.sleep(delay) print(f"Hello, {name} after {delay} seconds!") async def main(): tasks = [ asyncio.create_task(greet("Alice", 2)), asyncio.create_task(greet("Bob", 1)), asyncio.create_task(greet("Carol", 3)), ] await asyncio.gather(*tasks) # Wait for all tasks to finish asyncio.run(main())import asyncio async def greet(name, delay): await asyncio.sleep(delay) print(f"Hello, {name} after {delay} seconds!") async def main(): tasks = [ asyncio.create_task(greet("Alice", 2)), asyncio.create_task(greet("Bob", 1)), asyncio.create_task(greet("Carol", 3)), ] try: await asyncio.wait_for(asyncio.gather(*tasks), timeout=2.5) except asyncio.TimeoutError: print("Timed out!") for t in tasks: t.cancel() asyncio.run(main())
Python Tools
Libraries
- tqdm - Progress bar in commandline like 76%|████████████████████████ | 7568/10000 [00:33<00:10, 229.00it/s]