Comprehensive Python Cheat Sheet: Version Differences, Core Libraries, Advanced Topics, and Code Samples
This extensive guide covers Python 2 vs 3 differences, conversion tools, essential and advanced libraries, concurrency patterns, design patterns, database and system fundamentals, along with numerous code snippets and practical examples for developers seeking a deep understanding of Python programming.
This document is a detailed collection of Python notes and examples compiled by a developer, covering language differences, useful libraries, advanced concepts, design patterns, and system-level knowledge.
Py2 VS Py3
print becomes a function; in Python 2 it is a keyword.
unicode is default str in Python 3.
Division returns float.
long type removed.
xrange replaced by range.
Support for Chinese identifiers.
Advanced unpacking and * unpacking.
Keyword‑only arguments require name=value.
raise from syntax.
dict.iteritems renamed to items().
yield from for delegating to sub‑generators.
asyncio, async/await native coroutine support.
New modules: enum, mock, ipaddress, concurrent.futures, asyncio, urllib, selector.
Py2/3 Conversion Tools
six module for compatibility.
2to3 tool to convert syntax.
__future__ imports to use upcoming features.
Common Libraries
collections – essential data structures.
heapq – priority queue operations.
itertools – advanced iterator utilities.
contextlib – context manager helpers.
types – includes coroutine support via types.coroutine.
html – HTML escaping and unescaping.
mock – testing mocks.
concurrent.futures – thread and process pools.
asyncio – asynchronous I/O framework.
multiprocessing – Manager, Pipe, Queue, Pool examples.
sys – argv, path, modules, exit.
time – default time functions.
inspect, cProfile, bisect, fnmatch, timeit – various utilities.
Enum Example
<span style="color: #5c6370; font-style: italic;"># 枚举的注意事项</span>
from enum import Enum
class COLOR(Enum):
YELLOW = 1
GREEN = 1 # alias, no error
BLACK = 3
RED = 4
print(COLOR.GREEN) # prints COLOR.YELLOW
for i in COLOR:
print(i)Concurrency and Async
Examples of using ThreadPoolExecutor, asyncio futures, tasks, loops, and coroutine locks.
import asyncio
future = asyncio.ensure_future(coro)
loop.run_until_complete(future)Multiprocessing Examples
from multiprocessing import Manager, Process
def add_data(p_dict, key, value):
p_dict[key] = value
if __name__ == "__main__":
progress_dict = Manager().dict()
p1 = Process(target=add_data, args=(progress_dict, "bobby1", 22))
p2 = Process(target=add_data, args=(progress_dict, "bobby2", 23))
p1.start(); p2.start()
p1.join(); p2.join()
print(progress_dict)Design Patterns
Singleton, Factory, Builder examples in Python.
# Singleton via __new__
class Single:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super().__new__(cls)
return cls._instanceDatabase Topics
MySQL index evolution, clustering, InnoDB vs MyISAM, index usage rules, aggregation, and query optimization tips.
Redis Overview
High performance due to in‑memory, single‑threaded design.
Data types: strings, lists, hashes, sets, sorted sets, bitmaps, hyperloglog.
Persistence: RDB snapshots and AOF logs.
Transactions via MULTI/EXEC, WATCH.
Distributed lock pattern using SETNX with expiration.
Common issues: cache avalanche, penetration, snowball, pre‑warming, degradation.
Linux and System Knowledge
IO models: select, poll, epoll, blocking, non‑blocking, signal‑driven, async.
Process management: kill -9 vs -15.
Memory management: paging vs segmentation.
Monitoring tools: top, free.
Algorithms and Data Structures
Implementations of quick sort, merge sort, heap sort, binary search, stack, queue, linked list operations, and tree manipulations.
def quick_sort(arr):
if len(arr) < 2:
return arr
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)Interview Preparation
Advanced questions on database design, distributed locks, short‑URL services, seckill systems, and algorithmic challenges.
--- End of Summary ---
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
