InkdownInkdown
Start writing

Study

59 filesยท8 subfolders

Shared Workspace

Study
core

Basics

Shared from "Study" on Inkdown

Python Basics (Engineer Cheat Sheet)

Environment & Tooling

pyenv + venv
  • pyenv is a Python version manager, similar to nvm for Node.js.
  • It helps you install and switch between multiple Python versions.
  • venv creates an isolated environment for one project, so packages from one project do not affect another.
programming-language-concepts.md
zero-language-explanation.md
DB
01-introduction.md
02-relational-databases.md
03-database-design.md
04-indexing.md
05-transactions-acid.md
06-nosql-databases.md
07-query-optimization.md
08-replication-ha.md
09-sharding-partitioning.md
10-caching-strategies.md
11-cap-theorem.md
12-connection-pooling.md
13-backup-recovery.md
14-monitoring.md
15-database-selection.md
README.md
JS
Event loop
Merlin Backend
01-Orchestration.md
02-DeepResearch.md
03-Search.md
04-Scraping.md
05-Streaming.md
06-MultiProviderLLM.md
07-MemoryAndContext.md
08-ErrorHandling.md
09-RateLimiting.md
10-TaskQueue.md
11-SecurityAndAuth.md
Orchestration-2nd-draft
OpenAI Agents Python
00_OVERVIEW.md
01_AGENT_SYSTEM.md
02_RUNNER_SYSTEM.md
03_TOOL_SYSTEM.md
04_ITEMS_SYSTEM.md
05_GUARDRAILS.md
06_HANDOFFS.md
07_MEMORY_SESSIONS.md
08_MODEL_PROVIDERS.md
09_SANDBOX_SYSTEM.md
10_TRACING.md
11_RUN_STATE.md
12_CONTEXT.md
13_LIFECYCLE_HOOKS.md
14_CONFIGURATION.md
15_ERROR_HANDLING.md
16_STREAMING.md
17_EXTENSIONS.md
18_MCP_INTEGRATION.md
19_BEST_PRACTICES.md
20_ARCHITECTURE_PATTERNS.md
opencode-study
context-handling
core
Python
Alembic
Basics
sqlalchemy - fastapi
SQLAlchemy overview
tweets
system_design_for_agentic_apps.md

Example:

Bash
pyenv install 3.11.6
pyenv local 3.11.6

python -m venv venv
source venv/bin/activate   # macOS / Linux
venv\Scripts\activate      # Windows
pip + requirements.txt
  • pip is Pythonโ€™s package installer.
  • requirements.txt stores the list of dependencies for a project.
  • This makes it easy for others, or your future self, to install the same packages.

Example:

Bash
pip install fastapi
pip freeze > requirements.txt
pip install -r requirements.txt
Poetry (pyproject.toml)
  • Poetry is a modern dependency and project manager for Python.
  • It handles dependencies, virtual environments, and package configuration in one place.
  • pyproject.toml is the main config file Poetry uses.

Example:

Bash
poetry init
poetry add fastapi
poetry install
Python REPL + ipython
  • REPL means Read-Eval-Print Loop.
  • It is a quick interactive shell where you can test Python code.
  • ipython is a better REPL with autocomplete, command history, and nicer output.

Example:

Bash
python
>>> 2 + 2

ipython
In [1]: 2 + 2

Syntax โ€” Whatโ€™s Different from TS/JS

Indentation, no braces
  • Python uses indentation to define code blocks.
  • It does not use {} like JavaScript or TypeScript.
  • A colon : starts a new block.

Example:

Python
if x > 10:
    print("big")
else:
    print("small")
Type hints
  • Type hints let you describe what type a variable or function argument should be.
  • They make code easier to understand and improve editor support.
  • They are not strictly enforced by Python at runtime by default.

Example:

Python
def add(a: int, b: int) -> int:
    return a + b
f-strings
  • f-strings are the cleanest way to insert variables into strings.
  • Put f before the string, then use {} inside it.

Example:

Python
name = "Shubho"
age = 21
print(f"My name is {name} and I am {age} years old.")
None vs null / undefined
  • Python has None to represent โ€œno valueโ€.
  • There is no separate null or undefined.
  • The correct check is is None, not == None.

Example:

Python
x = None

if x is None:
    print("x has no value")
Truthiness
  • In Python, some values are treated as False in conditions.
  • Common falsy values are: None, 0, "", [], {}, set().
  • Most other values are truthy.

Example:

Python
items = []

if items:
    print("has items")
else:
    print("empty")
Walrus operator :=
  • The walrus operator assigns a value and uses it in the same expression.
  • It is useful when you want to avoid doing the same work twice.

Example:

Python
if (length := len("python")) > 5:
    print(length)

Collections & Comprehensions

list / dict / set / tuple
  • list: ordered, mutable collection
  • dict: key-value mapping
  • set: unordered collection of unique values
  • tuple: ordered, immutable collection

Example:

Python
my_list = [1, 2, 3]
my_dict = {"name": "Shubho", "age": 21}
my_set = {1, 2, 3}
my_tuple = (1, 2, 3)
List comprehensions
  • A compact way to create lists from loops.
  • Very common and very Pythonic.

Example:

Python
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums]
print(squares)

With condition:

Python
evens = [n for n in nums if n % 2 == 0]
print(evens)
Dict comprehensions
  • Similar to list comprehensions, but for dictionaries.
  • Useful when transforming data into key-value form.

Example:

Python
nums = [1, 2, 3]
squares = {n: n * n for n in nums}
print(squares)
Unpacking *args and **kwargs
  • *args collects extra positional arguments into a tuple.
  • **kwargs collects extra keyword arguments into a dictionary.
  • Useful when you do not know how many arguments will be passed.

Example:

Python
def show(*args, **kwargs):
    print(args)
    print(kwargs)

show(1, 2, 3, name="Shubho", role="Engineer")
Generators (yield)
  • A generator returns values one at a time instead of all at once.
  • This makes it memory-efficient.
  • It is useful for large data, streams, and lazy processing.

Example:

Python
def count_up_to(n):
    for i in range(1, n + 1):
        yield i

for num in count_up_to(3):
    print(num)

Functions & OOP

Default args, keyword args
  • Default arguments give a parameter a fallback value.
  • Keyword arguments let you pass values by name.
  • This makes function calls clearer and more flexible.

Example:

Python
def greet(name, message="Hello"):
    print(f"{message}, {name}")

greet("Shubho")
greet("Shubho", message="Welcome")
Keyword-only arguments
  • You can force some arguments to be passed by name using *.
  • This makes calls more explicit and avoids confusion.

Example:

Python
def create_user(name, *, admin=False):
    print(name, admin)

create_user("Shubho", admin=True)
Decorators
  • A decorator wraps a function and changes or extends its behavior.
  • Common uses: logging, authentication, caching, route handling.

Example:

Python
def log_call(fn):
    def wrapper():
        print("Function is running")
        return fn()
    return wrapper

@log_call
def say_hi():
    print("Hi")

say_hi()
dataclass
  • A dataclass is a simpler way to write classes that mostly store data.
  • It automatically creates methods like __init__ and __repr__.

Example:

Python
from dataclasses import dataclass

@dataclass
class User:
    name: str
    age: int

user = User("Shubho", 21)
print(user)
Dunder methods
  • Dunder means โ€œdouble underscoreโ€.
  • These special methods let your class behave in custom ways.
  • Examples: __init__, __str__, __len__, __getitem__.

Example:

Python
class Book:
    def __init__(self, title):
        self.title = title

    def __str__(self):
        return f"Book: {self.title}"

book = Book("Python Basics")
print(book)
Context managers (with)
  • A context manager handles setup and cleanup automatically.
  • It is commonly used for files, database connections, and locks.
  • Even if an error happens, cleanup still runs.

Example:

Python
with open("notes.txt", "r") as file:
    content = file.read()
    print(content)

Error Handling & Modules

try / except / finally
  • try contains code that may fail.
  • except handles the error.
  • finally always runs, whether there was an error or not.

Example:

Python
try:
    num = int("abc")
except ValueError as e:
    print("Conversion failed:", e)
finally:
    print("This always runs")
Custom exceptions
  • You can create your own exception types for clearer error handling.
  • This makes bigger applications easier to maintain.

Example:

Python
class AppError(Exception):
    pass

raise AppError("Something went wrong in the app")
Imports
  • import lets you use code from another file or module.
  • This helps organize code into reusable parts.

Example:

Python
import math

print(math.sqrt(16))
__init__.py
  • __init__.py tells Python that a folder should behave like a package.
  • It can also run package setup code or expose selected imports.

Example folder structure:

Python
mypackage/
    __init__.py
    utils.py

Import example:

Python
from mypackage.utils import my_function

Mental Model

Python is interpreted
  • Python code is executed by the Python interpreter.
  • You do not usually compile it manually like C or C++.
Python is dynamically typed
  • You do not need to declare variable types beforehand.
  • A variable can point to different types of values over time.

Example:

Python
x = 10
x = "hello"
Everything is an object
  • Numbers, strings, functions, classes, everything in Python is an object.
  • That is why Python feels very consistent.

Example:

Python
x = "hello"
print(type(x))
Clean code matters a lot in Python
  • Python is built around readability.
  • Simple, clear code is preferred over clever but confusing code.

What to Learn Next

async / await
  • Used for asynchronous programming.
  • Important for APIs, web servers, and I/O-heavy systems.
FastAPI
  • A modern Python web framework.
  • Great for building APIs quickly.
Pydantic
  • Used for validation and structured data handling.
  • Common in FastAPI apps.
File handling and streams
  • Important for working with files, uploads, logs, and data pipelines.
Concurrency
  • Learn the difference between threads, processes, and async tasks.
Packaging and deployment
  • Important for shipping real Python applications.