A curated collection of Python code examples demonstrating practical programming concepts, performance optimizations, and real-world implementations. Perfect for developers looking to learn new techniques, compare approaches, or find reference implementations.
This repository contains 40+ Python examples covering:
- Performance Comparisons - See how different libraries and approaches stack up
- Algorithm Implementations - Classic data structures and algorithms
- Web Development - FastAPI, async programming, and HTTP patterns
- Database Integration - MongoDB, embeddings, and data processing
- Advanced Python - Context managers, generators, decorators, and more
- External APIs - Authentication, web scraping, and service integration
- Python 3.13 (specified in
.python-version
) - Individual examples may require specific packages (install as needed)
# Clone and explore
git clone <repository-url>
cd CodeExamples
# Run any example directly
python code/BloomFilter.py
python code/merge_intervals.py
python code/orjson_vs_json.py
Perfect your resource management and API rate limiting:
# From context_manager_throttle_rate.py
from contextlib import contextmanager
import time
@contextmanager
def throttle(seconds):
yield
time.sleep(seconds)
# Usage: Never get rate-limited again!
for _ in range(5):
with throttle(1): # Pause 1 second between calls
ping_api()
Clean, efficient interval merging:
# From merge_intervals.py
def merge_intervals(intervals):
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
merged[-1][1] = max(merged[-1][1], interval[1])
return merged
# Example: [[15,18], [8,10], [1,3], [2,6]] โ [[1,6], [8,10], [15,18]]
Handle massive files without breaking a sweat:
# From iterator_generator.py
def take_n(n, itr):
result = []
for i in range(n):
try:
result.append(next(itr))
except StopIteration:
break
return result
# Process huge files efficiently
with open('my_huge_file.txt', 'r') as FILE:
results = take_n(3, filter(find_my_pattern,
(line for line in FILE)))
Production-ready password hashing with salt:
# From password_hash.py
import hashlib, os
password = "mypassword123"
salt = os.urandom(16)
# Strong password hashing
hashed = hashlib.pbkdf2_hmac(
'sha256', # Hash algorithm
password.encode('utf-8'), # Convert to bytes
salt, # Random salt
100_000 # Iterations (security)
)
Make your code more readable and maintainable:
# From enums_examples.py
from enum import Enum
class UserRole(Enum):
ADMIN = 1
EDITOR = 2
VIEWER = 3
def can_edit(self):
return self in {UserRole.ADMIN, UserRole.EDITOR}
def can_delete(self):
return self == UserRole.ADMIN
# Clean usage
if user_role.can_edit():
print("User can edit content")
Real benchmarks with actual numbers:
# From orjson_vs_json.py
import json, orjson, time
data = [{"id": i, "value": f"value-{i}"} for i in range(1_000_000)]
# Standard json
start = time.time()
json.dumps(data)
json_time = time.time() - start
# orjson
start = time.time()
orjson.dumps(data)
orjson_time = time.time() - start
print(f"orjson is {json_time/orjson_time:.2f}x faster!")
# Typical result: orjson is 2-3x faster!
Space-efficient membership testing:
# From BloomFilter.py
class BloomFilter:
def __init__(self, n_items, fp_rate=0.01):
self.m = -int(n_items * math.log(fp_rate) / (math.log(2)**2))
self.k = max(1, int((self.m / n_items) * math.log(2)))
self.bitarr = bytearray((self.m + 7) // 8)
def add(self, item):
for pos in self._hashes(item):
self.bitarr[pos // 8] |= 1 << (pos % 8)
def __contains__(self, item):
return all(self.bitarr[pos // 8] & (1 << (pos % 8))
for pos in self._hashes(item))
# Test millions of items with tiny memory footprint!
When Python isn't fast enough:
# From cyton_fast_sum.pyx
def fast_sum(long long[:] arr):
cdef long long total = 0
for i in range(arr.shape[0]):
total += arr[i]
return total
# Benchmark shows 10-50x speedup over pure Python!
orjson_vs_json.py
- JSON serialization benchmarksnumpy_vs_numexpr.py
- Numerical computation comparisonslist_comp_vs_manual.py
- List comprehension vs traditional loopscyton_example.py
- Cython performance testingprofile_function.py
- Code profiling techniques
BloomFilter.py
- Probabilistic data structure implementationKth_largest_element.py
- Efficient selection algorithmmerge_intervals.py
- Interval merging algorithmget_duplicates.py
- Duplicate detection using Counterprime_numbers.py
- Prime number generation
fastapi_dependency_injection.py
- Clean DI patternsfastapi_htmx.py
- Modern web interfacesasync_threads.py
- Concurrent request handlingcapture_headers.py
- HTTP header processing
context_manager_*.py
- Custom context managersiterator_generator.py
- Memory-efficient file processingenums_examples.py
- Clean enum usagepatterns_usage.py
- Design pattern implementationslogging_with_extra_parameter.py
- Advanced logging
password_hash.py
- Secure password handlingauth_by_pyseto.py
- Modern token authentication
openai_embeddings.py
- Vector search with MongoDBmongo_shard.py
- MongoDB operationsget_youtube_transcript.py
- API integration
Start with these fundamental examples:
merge_intervals.py
- Learn algorithm thinkingget_duplicates.py
- Understand data processingenums_examples.py
- Clean code patternsiterator_generator.py
- Memory efficiency
Level up with these examples:
context_manager_throttle_rate.py
- Advanced Python featuresfastapi_dependency_injection.py
- Web development patternsBloomFilter.py
- Data structure implementationpassword_hash.py
- Security practices
Master these complex topics:
async_threads.py
- Concurrent programmingcyton_example.py
- Performance optimizationopenai_embeddings.py
- AI/ML integrationpatterns_usage.py
- Design patterns
python code/BloomFilter.py
python code/merge_intervals.py
python code/orjson_vs_json.py
# FastAPI applications include uvicorn.run()
python code/async_threads.py
python code/fastapi_dependency_injection.py
# Then visit http://localhost:8000
# These show timing comparisons
python code/numpy_vs_numexpr.py
python code/list_comp_vs_manual.py
python code/orjson_vs_json.py
# Some examples require input
python code/password_hash.py
python code/login_to_upwork.py
Most examples are self-contained, but some may require:
# For performance examples
pip install orjson numexpr numpy
# For web examples
pip install fastapi uvicorn starlette
# For database examples
pip install pymongo requests
# For specific examples
pip install pyseto babel cython pydantic patterns
Found a bug? Have a cool example to add? Contributions welcome!
- Keep examples focused and well-documented
- Include timing comparisons for performance examples
- Follow the existing naming conventions (snake_case)
- Add docstrings explaining the concept demonstrated
- Check
WARP.md
for development guidance - Each example includes inline documentation
- Many examples include comparative analysis
- Look for related examples in similar categories
Happy Coding! ๐ Explore, learn, and build amazing things with Python.
"The best way to learn programming is by reading and writing code." - Start exploring! ๐