Fundamentals 31 min read

Comprehensive Python Cheat Sheet and Advanced Topics Summary

This article compiles an extensive Python reference covering Python 2 vs 3 differences, essential and advanced libraries, concurrency models, language internals, testing techniques, design patterns, data structures, algorithms, networking basics, MySQL and Redis insights, Linux I/O models, and performance‑optimization strategies, all illustrated with practical code snippets.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Comprehensive Python Cheat Sheet and Advanced Topics Summary

This document is a thorough Python reference that gathers key concepts, practical tips, and code examples for both beginners and experienced developers.

Python 2 vs Python 3 Differences

print is a function in Python 3, a keyword in Python 2.

Unicode is the default string type in Python 3.

Division (/) always returns a float.

long type removed; int has unlimited precision.

xrange replaced by range.

Support for Chinese identifiers.

Advanced unpacking and * unpacking.

Keyword‑only arguments require name=value after *.

raise from for exception chaining.

dict.items() replaces iteritems.

yield from to delegate to sub‑generators.

Native async/await and asyncio for asynchronous programming.

New standard library modules: enum, mock, ipaddress, concurrent.futures, selector, etc.

Enum Usage

# Enum example
from enum import Enum

class COLOR(Enum):
    YELLOW = 1
    GREEN = 1  # alias, same value as YELLOW
    BLACK = 3
    RED = 4

print(COLOR.GREEN)  # prints COLOR.YELLOW

# Iterate over enum members (aliases are skipped)
for i in COLOR:
    print(i)

# Iterate over all members including aliases
for name, member in COLOR.__members__.items():
    print(name, member)

Python 2/3 Migration Tools

six – compatibility library for writing code that runs on both versions.

2to3 – automatic source‑code conversion.

__future__ imports – enable newer language features.

Commonly Used Libraries

collections – essential container types.

heapq – heap‑based priority queue.

itertools – advanced iterator building blocks.

timeit – measure execution time of small code snippets.

contextlib – utilities for context managers.

types – access to built‑in type objects and coroutine support.

html – HTML escaping and unescaping.

unittest / pytest – unit testing frameworks.

coverage – test‑coverage measurement.

Advanced Topics

Multiprocessing and Inter‑Process Communication

from multiprocessing import Manager, Process, Pipe, Queue, Pool

# Shared dictionary via Manager
manager = Manager()
shared = manager.dict()

# Simple producer/consumer using Pipe
parent, child = Pipe()

def producer(p):
    p.send('data')

def consumer(p):
    print(p.recv())

p1 = Process(target=producer, args=(child,))
p2 = Process(target=consumer, args=(parent,))

p1.start(); p2.start()

Thread Pool and Process Pool

# Using a process pool
from multiprocessing import Pool

def task(x):
    return x * x

with Pool(4) as pool:
    results = pool.map(task, range(10))
print(results)

Asyncio Basics

import asyncio

async def hello():
    print('Hello')
    await asyncio.sleep(1)
    print('World')

loop = asyncio.get_event_loop()
loop.run_until_complete(hello())
loop.close()

GIL and Concurrency

The Global Interpreter Lock allows only one thread to execute Python bytecode at a time.

CPU‑bound tasks benefit from multiprocessing; I/O‑bound tasks benefit from threading or asyncio.

Metaclasses and Duck Typing

class Meta(type):
    def __new__(cls, name, bases, attrs):
        return super().__new__(cls, name, bases, attrs)

class MyClass(metaclass=Meta):
    pass

Python follows duck typing: an object is acceptable as long as it provides the required methods/attributes, regardless of its actual type.

Testing and Introspection

Use unittest.TestCase for class‑based tests.

Pytest discovers functions prefixed with test_ and provides fixtures.

Introspection functions: type() , isinstance() , getattr() , hasattr() , dir() .

Design Patterns

Singleton

class Singleton:
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance

Factory

def animal_factory(kind):
    if kind == 'dog':
        return Dog()
    if kind == 'cat':
        return Cat()
    raise ValueError('Unsupported animal')

Builder

Separate construction of a complex object (e.g., a computer) from its representation.

Data Structures and Algorithms

Sorting: quick sort, selection sort, insertion sort, merge sort, heap sort (via heapq.nsmallest ).

Searching: binary search implementation.

Containers: stack and queue built on collections.deque .

Linked list, binary tree, and graph basics are mentioned for interview preparation.

Networking Basics

HTTPS, HTTP status codes, request methods (idempotence, safety).

WSGI application skeleton.

RPC, CDN, SSL/TLS, SSH, TCP/UDP handshake details.

Common security concerns: XSS, CSRF, HttpOnly cookies.

MySQL Insights

Index evolution: linear → hash → B‑Tree → B+‑Tree.

When indexes become ineffective (leading % in LIKE, implicit type conversion, missing left‑most prefix, etc.).

Difference between InnoDB (clustered index) and MyISAM (non‑clustered).

Common pitfalls: using !=, OR, functions on indexed columns.

Redis Overview

Why Redis is fast: in‑memory, single‑threaded event loop, simple data structures.

Persistence: RDB snapshots and AOF logs.

Data types: strings, lists, hashes, sets, sorted sets, bitmaps, hyperloglog.

Transactions via MULTI/EXEC, distributed lock pattern using SETNX with expiration.

Cache problems: snowball, penetration, pre‑heat, update, degradation.

Linux I/O Models

Blocking, non‑blocking, multiplexed I/O (select/poll/epoll), signal‑driven, asynchronous (gevent/asyncio).

Process management: kill -15 (graceful) vs kill -9 (force).

Memory management: paging vs segmentation, top , free .

Performance Optimization Strategies

Algorithmic improvements and appropriate data structures.

Database tuning: proper indexing, slow‑query analysis, batch operations, using NoSQL caches.

Network optimization: request batching, Redis pipelines.

Asynchronous programming with asyncio or task queues like Celery.

Concurrency via multithreading, multiprocessing, or coroutine libraries (gevent).

Overall, the article serves as a dense cheat‑sheet for Python developers, covering language fundamentals, ecosystem tools, system‑level concepts, and interview‑ready knowledge.

design patternspythonConcurrencyProgrammingRedisLinuxdatabasesCheat Sheet
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.