Python Dev Config Cheatsheet
This cheatsheet covers common Python dev commands and snippets: venv, pip, data types, string methods, file I/O, module management, debugging, and more.
Virtual Environment Management (py-env)
``bash
# Create virtual environment
python -m venv venv
# Activate venv (Linux/macOS) source venv/bin/activate
# Activate venv (Windows PowerShell) venv\Scripts\Activate.ps1
# Deactivate venv deactivate
# Export installed packages pip freeze > requirements.txt
# Install from requirements file
pip install -r requirements.txt
`
Package Management (py-env)
`bash
# Install a package
pip install requests
# Install a specific version pip install requests==2.31.0
# Upgrade a package pip install --upgrade requests
# Uninstall a package pip uninstall requests -y
# List installed packages pip list
# Show package details pip show requests
# Install to user directory (no sudo) pip install --user package
# Check outdated packages
pip list --outdated
`
Core Data Types (py-data)
`python
# List operations
lst = [1, 2, 3]
lst.append(4) # [1, 2, 3, 4]
lst.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
lst.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6]
lst.remove(3) # [0, 1, 2, 4, 5, 6]
popped = lst.pop() # popped=6, lst=[0, 1, 2, 4, 5]
# Dictionary operations d = {'a': 1, 'b': 2} d['c'] = 3 # {'a': 1, 'b': 2, 'c': 3} d.get('x', 0) # 0 (with default) d.setdefault('y', 4) # set default if key missing d.keys() # dict_keys(['a', 'b', 'c']) d.values() # dict_values([1, 2, 3]) d.items() # dict_items([('a',1), ('b',2), ('c',3)])
# Set operations
s = {1, 2, 3}
s.add(4) # {1, 2, 3, 4}
s.discard(2) # {1, 3, 4}
s1 = {1, 2, 3}
s2 = {3, 4, 5}
s1 & s2 # {3} intersection
s1 | s2 # {1,2,3,4,5} union
s1 - s2 # {1, 2} difference
`
String Handling (py-string)
`python
s = " hello world "
s.strip() # "hello world"
s.upper() # " HELLO WORLD "
s.lower() # " hello world "
s.split() # ['hello', 'world']
'-'.join(['a','b']) # "a-b"
s.replace("world", "python") # " hello python "
s.startswith("hel") # True
s.find("world") # 8
s.count("l") # 3
# f-string formatting name = "Alice" age = 30 f"Name: {name}, Age: {age}" # "Name: Alice, Age: 30" f"{3.14159:.2f}" # "3.14" f"{1000:>10}" # " 1000" (right-aligned)
# String slicing
text = "python"
text[0:3] # "pyt"
text[::-1] # "nohtyp"
text[::2] # "pto"
`
File I/O (py-file)
`python
# Read file
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read() # read entirely
lines = f.readlines() # read lines into list
for line in f: # iterate line by line (memory-friendly)
print(line.strip())
# Write file with open('file.txt', 'w', encoding='utf-8') as f: f.write('hello\n') f.writelines(['line1\n', 'line2\n'])
# Append to file with open('file.txt', 'a', encoding='utf-8') as f: f.write('append this\n')
# JSON file operations import json data = {'name': 'Alice', 'scores': [90, 85]} with open('data.json', 'w') as f: json.dump(data, f, indent=2) with open('data.json') as f: loaded = json.load(f)
# Path operations
from pathlib import Path
p = Path('/home/user/file.txt')
p.name # "file.txt"
p.stem # "file"
p.suffix # ".txt"
p.parent # "/home/user"
p.exists() # True/False
p.mkdir(parents=True, exist_ok=True)
`
Modules & Argument Parsing (py-module)
`python
# argparse for CLI arguments
import argparse
parser = argparse.ArgumentParser(description='My script')
parser.add_argument('input', help='input file path')
parser.add_argument('-o', '--output', default='out.txt', help='output file')
parser.add_argument('-v', '--verbose', action='store_true', help='verbose mode')
parser.add_argument('--count', type=int, default=1, help='number of times')
args = parser.parse_args()
# sys module import sys sys.argv # CLI argument list sys.exit(0) # successful exit sys.exit(1) # error exit sys.path # module search path
# os module
import os
os.getcwd() # current working directory
os.listdir('.') # list directory contents
os.environ.get('HOME') # environment variable
os.path.join('dir', 'file.txt') # path join
`
Date & Random (py-module)
`python
# datetime
from datetime import datetime, timedelta
now = datetime.now()
now.strftime('%Y-%m-%d %H:%M:%S') # "2026-07-16 15:30:00"
datetime.strptime('2026-07-16', '%Y-%m-%d')
now + timedelta(days=7) # one week later
now - timedelta(hours=3) # three hours ago
# random
import random
random.random() # [0.0, 1.0) random float
random.randint(1, 10) # [1, 10] random integer
random.choice(['a','b','c']) # random choice
random.sample(range(100), 5) # non-repeating sample
random.shuffle(list) # shuffle in-place
`
Input/Output & Formatting (py-io)
`python
# Input
user_input = input("Enter name: ")
# Advanced print print("hello", "world", sep=", ") # hello, world print("loading", end="...\n") # custom end character print(f"value: {value:>10.2f}") # right-aligned, 2 decimals
# Exception handling try: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") except (ValueError, TypeError): print("Type or value error") else: print("No exception") finally: print("Always executed")
# Raise exceptions
raise ValueError("invalid value")
`
List Comprehensions & Debugging (py-debug)
``python # List comprehension squares = [x2 for x in range(10)] # [0, 1, 4, ..., 81] evens = [x for x in range(20) if x % 2 == 0] pairs = [(x, y) for x in [1,2] for y in [3,4]] # [(1,3),(1,4),(2,3),(2,4)]
# Dict comprehension square_dict = {x: x2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
# Set comprehension unique_lens = {len(w) for w in ["hi", "hello", "hey"]} # {2, 3, 5}
# Generator expression gen = (x2 for x in range(1000000)) # lazy evaluation sum(x2 for x in range(10)) # 285
# Pretty print from pprint import pprint data = {'users': [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]} pprint(data, indent=2, depth=2)
# Breakpoint debugger (Python 3.7+) # breakpoint() # launches pdb debugger
# Timer decorator import time def timer(func): def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) elapsed = time.perf_counter() - start print(f"{func.__name__} took: {elapsed:.4f}s") return result return wrapper
@timer def slow_function(): time.sleep(0.1) return "done"
Environment(8)
| Command | Level | ||
|---|---|---|---|
python -m venv venvCreate a Python virtual environment | Basic | python -m venv venv | |
source venv/bin/activateActivate virtual environment (Linux/macOS) | Basic | source venv/bin/activate | |
deactivateDeactivate virtual environment | Basic | deactivate | |
pip freeze > requirements.txtExport installed packages to file | Basic | pip freeze > requirements.txt | |
pip install -r requirements.txtInstall dependencies from requirements file | Basic | pip install -r requirements.txt | |
pip install requests==2.31.0Install a specific package version | Basic | pip install requests==2.31.0 | |
pip install --upgrade requestsUpgrade an installed package | Basic | pip install --upgrade requests | |
pip list --outdatedCheck outdated packages | Intermediate | pip list --outdated |
Data Types(5)
| Command | Level | ||
|---|---|---|---|
lst = [1, 2, 3]; lst.append(4)Append element to list | Basic | lst.append(4) | |
d.get('x', 0)Dict get with default value | Basic | d.get('x', 0) | |
d.setdefault('y', 4)Set dict default if key is missing | Intermediate | d.setdefault('y', 4) | |
s1 & s2Set intersection operation | Basic | s1 = {1,2,3}; s2 = {3,4,5}; s1 & s2 | |
s1 - s2Set difference operation | Basic | s1 = {1,2,3}; s2 = {3,4,5}; s1 - s2 |
Strings(5)
| Command | Level | ||
|---|---|---|---|
s.strip()Strip leading/trailing whitespace | Basic | s = " hello "; s.strip() | |
s.replace('world', 'python')String replace | Basic | s.replace('world', 'python') | |
'-'.join(['a', 'b'])Join string list with separator | Basic | '-'.join(['a', 'b']) | |
f'Name: {name}, Age: {age}'f-string formatted output | Basic | f'Name: {name}, Age: {age}' | |
text[::-1]Reverse string with step slicing | Intermediate | text[::-1] |
File I/O(5)
| Command | Level | ||
|---|---|---|---|
open('file.txt', 'r', encoding='utf-8')Open file in read mode (UTF-8) | Basic | with open('file.txt', 'r', encoding='utf-8') as f: | |
json.dump(data, f, indent=2)Serialize Python object to JSON file | Intermediate | json.dump(data, f, indent=2) | |
json.load(f)Load JSON file into Python object | Intermediate | with open('data.json') as f: data = json.load(f) | |
Path('/tmp/file.txt').suffixGet file extension | Basic | Path('/tmp/file.txt').suffix | |
p.mkdir(parents=True, exist_ok=True)Create directory recursively, no error if exists | Intermediate | p.mkdir(parents=True, exist_ok=True) |
Modules(8)
| Command | Level | ||
|---|---|---|---|
argparse.ArgumentParser(description='My script')Create CLI argument parser | Intermediate | parser = argparse.ArgumentParser(description='My script') | |
sys.argvGet CLI argument list | Basic | sys.argv | |
os.environ.get('HOME')Get environment variable | Basic | os.environ.get('HOME') | |
datetime.now().strftime('%Y-%m-%d %H:%M:%S')Get current time as formatted string | Basic | datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
random.randint(1, 10)Generate random integer in range | Basic | random.randint(1, 10) | |
random.sample(range(100), 5)Non-repeating random sample | Intermediate | random.sample(range(100), 5) | |
@contextmanagerCustom context manager with contextmanager decorator | Expert | from contextlib import contextmanager
@contextmanager
def managed_resource():
print("enter")
yield
print("exit")
with managed_resource():
print("inside") | |
lru_cacheFunction result caching with LRU strategy | Expert | from functools import lru_cache
@lru_cache(maxsize=128)
def expensive_func(n):
return n * n |
I/O(5)
| Command | Level | ||
|---|---|---|---|
input('Enter name: ')Read a line from stdin | Basic | input('Enter name: ') | |
print('hello', 'world', sep=', ')Print with custom separator | Basic | print('hello', 'world', sep=', ') | |
try ... except ... else ... finallyComplete exception handling structure | Intermediate | try:
result = 10 / 0
except ZeroDivisionError as e:
print(f'Error: {e}')
else:
print('No exception')
finally:
print('Always executed') | |
raise ValueError("invalid value")Manually raise an exception | Intermediate | raise ValueError('invalid value') | |
async with aiohttp.ClientSession() as session:Async HTTP request (asyncio + aiohttp) | Expert | async with aiohttp.ClientSession() as session:
async with session.get("https://api.example.com") as resp:
data = await resp.json() |
Debugging(5)
| Command | Level | ||
|---|---|---|---|
[x**2 for x in range(10)]List comprehension | Intermediate | [x**2 for x in range(10)] | |
{x: x**2 for x in range(5)}Dict comprehension | Intermediate | {x: x**2 for x in range(5)} | |
(x**2 for x in range(1000000))Generator expression (lazy evaluation) | Intermediate | (x**2 for x in range(1000000)) | |
breakpoint()Launch pdb interactive debugger (Python 3.7+) | Intermediate | breakpoint() | |
from pprint import pprint; pprint(data, indent=2)Pretty-print nested data structures | Basic | from pprint import pprint; pprint(data, indent=2) |