Executive Summary
Python in 2026 is the world's most popular programming language, holding the #1 position on TIOBE, GitHub Octoverse, and Stack Overflow surveys for the fourth consecutive year. Its dominance spans data science, machine learning, web development, automation, scripting, and increasingly systems-level work. Python 3.13 introduced an experimental free-threaded mode (PEP 703) that makes the GIL optional, and Python 3.14 brings template strings and deferred annotation evaluation. The packaging ecosystem has been transformed by uv (10-100x faster than pip) and Ruff (linting at Rust speed).
This report covers every major Python feature, from the six core data types through object-oriented programming, decorators, generators, context managers, type hints, and asyncio, to a comprehensive tour of the standard library and modern package management. Every section includes reference tables, practical code patterns, and data on adoption and ecosystem trends. Whether you are learning Python for the first time or are a senior engineer looking up a specific API, this guide is designed to be the single reference you need.
- FastAPI has surpassed Flask in popularity at 52% vs 22%, making it the most popular Python web framework in 2026. Django remains the choice for full-stack applications at 38%.
- Python 3.13 adoption has reached 35% within 18 months of release, making it the fastest adoption of any Python version. Python 3.12 holds 25%, and 3.14 is at 15% early adoption.
- uv has replaced pip for 40%+ of new projects, offering 10-100x faster dependency resolution and installation. The Astral ecosystem (uv + Ruff) is becoming the standard Python toolchain.
- The free-threaded CPython build (no GIL) is available experimentally in 3.13+, enabling true multi-threaded parallelism for the first time in Python's history. Major libraries (NumPy, Pandas) are adding free-threaded support.
#1
Most popular language (TIOBE)
52%
FastAPI adoption
35%
Python 3.13 adoption
100x
uv faster than pip
Part 1: Python Data Types
Python is dynamically typed: variables do not have types, values do. You do not declare types at assignment (x = 42 creates an int without any type annotation). Python has six core built-in types that form the foundation of all programs: int, float, str, bool, list, dict, tuple, set, and NoneType. Understanding the distinction between mutable and immutable types is fundamental to writing correct Python code.
Numeric Types: int, float, complex
int: Arbitrary-precision integers. Unlike C or Java, Python integers have no maximum value. 2**1000 works perfectly. Integers support standard arithmetic (+, -, *, /), integer division (//), modulo (%), and exponentiation (**). Division always returns a float (10 / 3 = 3.3333); use // for integer division (10 // 3 = 3). Numeric literals support underscore separators for readability: 1_000_000. Base literals: 0b1010 (binary), 0o17 (octal), 0xff (hex).
float: IEEE 754 double-precision (64-bit) floating-point numbers. About 15-17 significant decimal digits. Special values: float('inf'), float('-inf'), float('nan'). For exact decimal arithmetic (financial calculations), use the decimal module. For fractions, use the fractions module. Common pitfall: 0.1 + 0.2 != 0.3 in any IEEE 754 system; use math.isclose() for approximate comparison.
complex: Complex numbers with j suffix: 3+4j. Real and imaginary parts are floats. Access with .real and .imag attributes. The cmath module provides complex-valued math functions. Used in scientific computing, signal processing, and electrical engineering.
Strings (str)
Strings are immutable sequences of Unicode characters. Created with single quotes ('hello'), double quotes ("hello"), or triple quotes ('''multiline'''). Strings are sequences: indexable (s[0]), sliceable (s[1:3]), iterable (for c in s), and have a length (len(s)). Python strings support 40+ built-in methods covering search, transformation, testing, splitting, and formatting. f-strings (Python 3.6+) are the preferred formatting method: f"Name: {name}, Age: {age}".
Collections: list, tuple, dict, set
list: Mutable, ordered sequence. [1, 2, 3]. Supports indexing, slicing, appending, extending, inserting, removing, sorting, and reversing. Lists can contain any mix of types. List comprehensions ([x**2 for x in range(10)]) are the Pythonic way to create lists from transformations. Lists are implemented as dynamic arrays.
tuple: Immutable, ordered sequence. (1, 2, 3). Tuples are hashable (if all elements are hashable), so they can be dict keys and set elements. Use tuples for fixed collections: function returns, database rows, coordinate pairs. Named tuples (collections.namedtuple or typing.NamedTuple) add field names. Single-element tuple requires a trailing comma: (42,).
dict: Mutable, ordered (since Python 3.7) key-value mapping. {"name": "Alice", "age": 30}. Keys must be hashable (strings, numbers, tuples). O(1) average lookup, insertion, and deletion. Dict comprehensions: {k: v for k, v in items}. The | merge operator (3.9+) creates a new merged dict: d1 | d2. Dict views (keys(), values(), items()) are set-like and support set operations.
set: Mutable, unordered collection of unique hashable elements. {1, 2, 3}. O(1) membership testing (x in s). Set operations: union (|), intersection (&), difference (-), symmetric difference (^). frozenset is the immutable version. Sets are essential for deduplication and membership testing. Empty set must be created with set(), not {} (which creates an empty dict).
None and Booleans
None: Python's null value. The sole instance of NoneType. Used for default return values, optional parameters, and sentinel values. Always test with "is None" (identity), not "== None" (equality). None is falsy in boolean contexts. Functions without a return statement return None.
bool: True or False. A subclass of int (True == 1, False == 0). Falsy values: False, 0, 0.0, 0j, "", [], (), {}, set(), None, and objects whose __bool__() returns False. Everything else is truthy. The bool() built-in converts any value to its boolean equivalent.
Part 2: Functions and Scope
Functions are first-class objects in Python: they can be assigned to variables, passed as arguments, returned from other functions, and stored in data structures. Defined with the def keyword: def greet(name: str) -> str: return f"Hello, {name}!". Lambda functions provide anonymous single-expression functions: lambda x: x**2.
Parameters and Arguments
Python supports: positional parameters, keyword parameters, default values, *args (variable positional), **kwargs (variable keyword), positional-only (before /, PEP 570), and keyword-only (after *). The full signature: def f(pos_only, /, normal, *, kw_only, **kwargs). Default values are evaluated once at function definition time, not at each call. This means mutable defaults (def f(items=[])) are shared between calls. Use None sentinel pattern: def f(items=None): items = items or [].
Scope Rules (LEGB)
Python uses the LEGB rule for variable lookup: Local (inside current function), Enclosing (inside enclosing functions, for closures), Global (module-level), Built-in (Python built-in names). The global keyword lets a function modify a module-level variable. The nonlocal keyword (Python 3) lets a nested function modify a variable from its enclosing function scope. Without these keywords, assignment inside a function creates a local variable.
Closures
A closure is created when a nested function references variables from its enclosing scope. The inner function "closes over" those variables, retaining access even after the outer function returns. Closures are the mechanism behind decorators, factory functions, and callback patterns. The nonlocal keyword allows modifying enclosed variables. Example: def counter(): count = 0; def increment(): nonlocal count; count += 1; return count; return increment.
Higher-Order Functions and functools
Higher-order functions take functions as arguments or return functions. Built-in: map(), filter(), sorted() with key=. The functools module provides: @lru_cache/@cache (memoization), @wraps (preserve function metadata in decorators), partial (partial function application), reduce (fold operation), and @singledispatch (single-dispatch generic functions). functools.cached_property is a descriptor that computes a value once and caches it as an instance attribute.
Part 3: Object-Oriented Programming and Classes
Everything in Python is an object: integers, strings, functions, modules, and classes themselves. Python supports classes with single and multiple inheritance, properties, class methods, static methods, abstract base classes, and a rich set of special ("dunder") methods for operator overloading and protocol implementation.
Class Basics
Classes are defined with the class keyword. __init__ is the constructor (initializer). self is the conventional name for the instance reference (mandatory first parameter in instance methods). Instance attributes are created by assigning to self.attribute in __init__. Class attributes are shared across all instances. Python has no access modifiers (public/private/protected); by convention, _name indicates "protected" and __name triggers name mangling (becomes _ClassName__name).
Inheritance and MRO
Python supports single and multiple inheritance. The Method Resolution Order (MRO) uses C3 linearization to determine which method is called. View MRO with ClassName.__mro__ or ClassName.mro(). super() returns a proxy that follows the MRO, enabling cooperative multiple inheritance. The diamond problem is resolved by C3. Best practice: prefer composition over inheritance; use mixins for adding specific capabilities.
Dataclasses (Python 3.7+)
The @dataclass decorator (PEP 557) automatically generates __init__, __repr__, __eq__, and optionally __hash__, __lt__/__gt__/__le__/__ge__, and __post_init__ from annotated class fields. dataclasses reduce boilerplate for data-holding classes. Options: frozen=True (immutable), slots=True (use __slots__ for memory savings, 3.10+), kw_only=True (all fields keyword-only, 3.10+). Field-level options: field(default=..., default_factory=..., repr=False, compare=False).
Special (Dunder) Methods
Python uses double-underscore methods to define how objects interact with operators and built-in functions. Key dunders: __init__ (construction), __str__ (human-readable string), __repr__ (developer string), __len__ (len()), __getitem__/__setitem__ (indexing), __iter__/__next__ (iteration), __eq__/__lt__ etc. (comparison), __add__/__mul__ etc. (arithmetic), __enter__/__exit__ (context manager), __call__ (callable object), __hash__ (hashability), __contains__ (in operator).
Properties and Descriptors
The @property decorator creates managed attributes with getter, setter, and deleter methods that look like simple attribute access. Properties enforce encapsulation while maintaining a clean API. Descriptors are the underlying mechanism: objects with __get__, __set__, and/or __delete__ methods. Descriptors power properties, methods, classmethod, staticmethod, and __slots__. Data descriptors (with __set__) take priority over instance dictionaries.
Part 4: Decorators
A decorator is a function that takes another function (or class) and returns a modified version of it. The @decorator syntax is sugar for function = decorator(function). Decorators enable aspect-oriented programming: adding cross-cutting concerns (logging, timing, caching, access control, validation) without modifying the original function code.
Basic pattern: def my_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): # before; result = func(*args, **kwargs); # after; return result; return wrapper. Always use @functools.wraps to preserve the original function's __name__, __doc__, __module__, and __qualname__. Without it, the decorated function loses its identity, breaking help() and debugging.
Decorators with arguments require an extra layer: def repeat(n): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for _ in range(n): result = func(*args, **kwargs); return result; return wrapper; return decorator. Usage: @repeat(3). This three-level nesting is the standard pattern for parameterized decorators.
Class-based decorators implement __call__: class Timer: def __init__(self, func): self.func = func; def __call__(self, *args, **kwargs): start = time.time(); result = self.func(*args, **kwargs); print(f"Took {time.time()-start}s"); return result. Class decorators on classes themselves can modify class creation: @dataclass, @total_ordering, @register.
Common built-in and stdlib decorators: @property (managed attributes), @staticmethod (no self/cls), @classmethod (cls as first arg), @functools.lru_cache (memoization with maxsize), @functools.cache (unlimited memoization, 3.9+), @functools.wraps (preserve metadata), @functools.singledispatch (single-dispatch generic functions), @functools.cached_property (one-time computation), @abc.abstractmethod (enforce interface), @contextlib.contextmanager (generator-based context managers).
Part 5: Generators and Iterators
The iterator protocol is fundamental to Python. Any object that implements __iter__ (returns self) and __next__ (returns next value or raises StopIteration) is an iterator. All for loops, comprehensions, unpacking operations, and many built-in functions work through the iterator protocol. Iterables (lists, strings, dicts, files) produce iterators via their __iter__ method.
Generators are the easiest way to create iterators. A generator function uses yield to produce values one at a time, suspending state between calls. When next() is called, execution resumes from where it left off. This lazy evaluation means generators use constant memory regardless of how many values they produce. A generator for range(1_000_000_000) uses almost no memory, while a list would use 8+ GB.
Generator expressions provide a concise syntax: (x**2 for x in range(10)). They are like list comprehensions but produce values lazily. Use generator expressions when you only need to iterate once and do not need random access. They are commonly used with functions that consume iterables: sum(x**2 for x in range(10)), ",".join(str(x) for x in items).
yield from (PEP 380, Python 3.3) delegates to a sub-iterator: yield from iterable replaces for item in iterable: yield item but also handles send(), throw(), and close() correctly. This is essential for composing generator pipelines and implementing recursive generators (e.g., tree traversal).
The itertools module provides fast, memory-efficient building blocks for iterator-based programming: chain (concatenate), islice (slice iterators), product (Cartesian product), permutations, combinations, groupby, cycle, repeat, accumulate, zip_longest, starmap, tee, and more. Mastering itertools is key to writing efficient, Pythonic data processing code.
Part 6: Context Managers
Context managers guarantee cleanup code runs even if exceptions occur. The with statement calls __enter__ on entry and __exit__ on exit (whether by normal completion, exception, or return). The most common use is file handling: with open("file.txt") as f: data = f.read(). The file is automatically closed when the with block exits, even if an exception occurs during reading.
Creating context managers with classes: implement __enter__ (returns the resource) and __exit__ (handles cleanup, receives exception info). The __exit__ method receives (exc_type, exc_val, exc_tb) and can suppress exceptions by returning True. Common uses: database connections, locks, temporary directories, timing blocks, and transaction management.
The @contextlib.contextmanager decorator creates context managers from generators. The generator yields once: code before yield runs on __enter__, code after yield runs on __exit__. This is often simpler than the class-based approach. contextlib also provides: suppress() (ignore specific exceptions), redirect_stdout/stderr(), ExitStack (manage multiple context managers dynamically), nullcontext() (no-op context manager), and closing() (call .close() on exit).
Python 3.10 added parenthesized multi-line context managers: with (open("a") as a, open("b") as b). Python 3.13 supports "using" declarations for async resource management in the style of explicit resource management (PEP 707). async with statements handle asynchronous context managers (__aenter__/__aexit__) for async database connections, HTTP sessions, and similar resources.
Part 7: Type Hints
Type hints (PEP 484, Python 3.5+) annotate function parameters and return values with expected types. They are not enforced at runtime but are checked by static type checkers (mypy, pyright, pytype) and used by IDEs for autocomplete and error detection. Type hints serve as executable documentation and catch bugs before runtime. Python 3.9+ allows generic types in standard collections (list[int] instead of typing.List[int]). Python 3.10+ supports the | union syntax (int | str instead of Union[int, str]).
Core type annotations: str, int, float, bool, None, list[str], dict[str, int], tuple[int, str], set[float], Optional[str] (equivalent to str | None), Any (any type), Union[int, str] (or int | str in 3.10+). For function signatures: def greet(name: str, age: int = 0) -> str. For variables: x: int = 42. Collections with generic types: def process(items: list[dict[str, Any]]) -> list[str].
Advanced typing features: TypeVar (generic type variables), Generic (generic classes), Protocol (structural subtyping / duck typing in the type system, PEP 544), TypedDict (typed dictionaries), Literal (restrict to specific values), Final (cannot be reassigned), Annotated (attach metadata to types), ParamSpec (generic callable signatures), TypeVarTuple (variadic generics). Python 3.12 introduced the simpler type parameter syntax: def first[T](items: list[T]) -> T (PEP 695).
Practical type checking workflow: (1) Annotate function signatures first (parameters and return types). (2) Run mypy or pyright in CI/CD. (3) Gradually add annotations to existing code (gradual typing). (4) Use strict mode for new projects. (5) Use reveal_type() for debugging inferred types. (6) Configure with pyproject.toml: [tool.mypy] strict = true. Type checking catches real bugs: wrong argument types, missing return statements, None-safety violations, and incorrect container element types.
Part 8: Asyncio and Concurrency
asyncio is Python's built-in framework for writing concurrent code using async/await syntax. It is designed for I/O-bound operations: HTTP requests, database queries, file I/O, and network communication. asyncio uses a single-threaded event loop that manages coroutines cooperatively: when one coroutine awaits an I/O operation, the event loop runs another coroutine instead of blocking.
Coroutines are defined with async def and suspended with await. asyncio.run(main()) is the standard entry point that creates and runs the event loop. asyncio.gather(*coros) runs multiple coroutines concurrently and collects results. asyncio.create_task(coro) schedules a coroutine without waiting for it. TaskGroup (Python 3.11+, PEP 654) provides structured concurrency: async with asyncio.TaskGroup() as tg: tg.create_task(coro1()); tg.create_task(coro2()). All tasks are automatically awaited and exceptions propagated.
Key asyncio APIs: asyncio.sleep(seconds) (non-blocking delay), asyncio.Queue (producer-consumer pattern), asyncio.Lock/Event/Semaphore (synchronization), asyncio.wait_for(coro, timeout) (timeout wrapper), asyncio.shield(coro) (protect from cancellation), asyncio.to_thread(fn, *args) (run blocking code in a thread). For HTTP: use httpx or aiohttp. For databases: use asyncpg, aiomysql, or async SQLAlchemy.
Python concurrency options beyond asyncio: threading (concurrent I/O, limited by GIL for CPU), multiprocessing (parallel CPU work, separate processes), concurrent.futures (high-level ThreadPoolExecutor and ProcessPoolExecutor), and the new free-threaded CPython (3.13+, no GIL, true multi-threaded parallelism). Choose asyncio for many concurrent I/O operations (thousands of connections), threading for moderate concurrency with blocking libraries, and multiprocessing for CPU-intensive parallelism.
Part 9: Standard Library Tour
Python's "batteries included" philosophy means the standard library provides modules for nearly every common task. This section covers the most important modules that every Python developer should know.
os and sys
os: Operating system interface. os.path (path manipulation, largely replaced by pathlib), os.environ (environment variables), os.getcwd(), os.listdir(), os.makedirs(), os.remove(), os.rename(), os.walk() (directory tree traversal), os.getenv(). sys: System-specific parameters. sys.argv (command-line arguments), sys.path (module search path), sys.stdin/stdout/stderr, sys.exit(), sys.version, sys.platform, sys.getsizeof() (object memory size).
json
The json module serializes Python objects to JSON and deserializes JSON to Python. json.dumps(obj) produces a JSON string. json.loads(s) parses a JSON string. json.dump(obj, file) writes to a file. json.load(file) reads from a file. Options: indent (pretty-print), default (custom serializer for non-standard types), sort_keys, ensure_ascii. For custom objects, provide a default function or create a JSONEncoder subclass.
re (Regular Expressions)
The re module provides Perl-style regular expressions. Key functions: re.search(pattern, string) (first match), re.match(pattern, string) (match at start), re.findall(pattern, string) (all matches), re.sub(pattern, repl, string) (replace), re.split(pattern, string) (split). Compile patterns for reuse: pattern = re.compile(r"\d+"). Use raw strings (r"...") to avoid backslash escaping issues. Named groups: (?P<name>pattern).
datetime and zoneinfo
The datetime module provides date and time types. datetime.datetime.now() (current local time), datetime.datetime.utcnow() (UTC, prefer datetime.now(timezone.utc)), datetime.date.today(), timedelta for arithmetic. The zoneinfo module (Python 3.9+) provides IANA timezone support: from zoneinfo import ZoneInfo; dt = datetime.now(ZoneInfo("America/New_York")). Always store datetimes in UTC and convert to local time for display.
collections
Specialized container types: defaultdict (factory for missing keys), Counter (count occurrences), OrderedDict (ordered dict, mostly unnecessary since 3.7), deque (double-ended queue, O(1) append/pop on both ends), namedtuple (tuple with named fields), ChainMap (combine multiple dicts). collections.abc provides abstract base classes for containers: Iterable, Iterator, Sequence, Mapping, MutableMapping, Callable.
itertools
Iterator building blocks for efficient looping. Infinite iterators: count(), cycle(), repeat(). Terminating iterators: chain(), compress(), dropwhile(), takewhile(), groupby(), islice(), starmap(), accumulate(), zip_longest(). Combinatoric iterators: product() (Cartesian product), permutations(), combinations(), combinations_with_replacement(). All functions return lazy iterators, not lists.
pathlib
Object-oriented filesystem paths (Python 3.4+). Path objects use the / operator for joining: Path("src") / "main.py". Key methods: .read_text(), .write_text(), .read_bytes(), .exists(), .is_file(), .is_dir(), .mkdir(parents=True), .glob("*.py"), .rglob("**/*.py") (recursive), .stat(), .name, .stem, .suffix, .parent, .resolve() (absolute path). Python 3.12 added Path.walk() as a replacement for os.walk(). Preferred over os.path for all new code.
Part 10: Package Management
Python packaging has evolved dramatically. The 2026 landscape offers three main approaches: pip (traditional, universal), Poetry (modern, batteries-included), and uv (blazing fast, Rust-powered). All three use PyPI (Python Package Index) as the package source. pyproject.toml (PEP 518/621) is the standard project configuration file, replacing the legacy setup.py.
pip
The standard package installer, bundled with Python. Commands: pip install package, pip install -r requirements.txt, pip install -e . (editable install), pip freeze > requirements.txt, pip uninstall package, pip list, pip show package. Supports version specifiers: package==1.2.3 (exact), package>=1.2 (minimum), package~=1.2 (compatible release). Virtual environments: python -m venv .venv.
Poetry
A modern dependency management and packaging tool. Uses pyproject.toml for project metadata and poetry.lock for reproducible installs. Commands: poetry init, poetry add package, poetry install, poetry update, poetry build, poetry publish. Features: automatic virtual environment management, dependency groups (dev, test, docs), version constraints with sensible defaults, and script definitions. Ideal for application projects that need reproducible builds.
uv
An extremely fast Python package installer and resolver written in Rust by Astral (creators of Ruff). Drop-in replacement for pip and pip-tools. 10-100x faster than pip for resolution and installation. Commands: uv pip install package, uv pip compile requirements.in, uv pip sync requirements.txt, uv venv (create virtual environment), uvx (run tools without installing). uv also manages Python versions: uv python install 3.13. Rapidly becoming the default tool for Python dependency management.
Python Web Framework Popularity (2019-2026)
Source: OnlineTools4Free Research
Part 11: Built-in Functions Reference (68+)
Python provides 68+ built-in functions available without any import. This searchable, sortable reference table covers every built-in function with signature, description, example, and category.
Python Built-in Functions (68+)
69 rows
| Function | Signature | Description | Example | Category |
|---|---|---|---|---|
| abs() | abs(x) | Returns the absolute value of a number. | abs(-5) # 5 | Math |
| all() | all(iterable) | Returns True if all elements of the iterable are true (or iterable is empty). | all([1, 2, 3]) # True | Iterable |
| any() | any(iterable) | Returns True if any element of the iterable is true. | any([0, 1, 0]) # True | Iterable |
| ascii() | ascii(object) | Returns a printable representation with non-ASCII characters escaped. | ascii("cafe\u0301") # "'caf\\xe9'" | String |
| bin() | bin(x) | Converts an integer to a binary string prefixed with "0b". | bin(10) # "0b1010" | Conversion |
| bool() | bool([x]) | Converts a value to Boolean. Falsy: 0, None, empty containers. | bool([]) # False | Type |
| breakpoint() | breakpoint(*args, **kws) | Drops into the debugger at the call site. Uses PYTHONBREAKPOINT env var. | breakpoint() | Debug |
| bytearray() | bytearray([source]) | Returns a mutable sequence of bytes. | bytearray(b"abc") | Type |
| bytes() | bytes([source]) | Returns an immutable sequence of bytes. | bytes(5) # b"\x00\x00\x00\x00\x00" | Type |
| callable() | callable(object) | Returns True if the object appears callable. | callable(len) # True | Inspect |
| chr() | chr(i) | Returns the string of one character whose Unicode code point is the integer i. | chr(65) # "A" | String |
| classmethod() | @classmethod | Transforms a method into a class method receiving cls as first argument. | @classmethod def create(cls): ... | OOP |
| compile() | compile(source, filename, mode) | Compiles source into a code object that can be executed by exec() or eval(). | compile("x+1", "<string>", "eval") | Code |
| complex() | complex([real[, imag]]) | Creates a complex number. | complex(1, 2) # (1+2j) | Type |
| delattr() | delattr(object, name) | Deletes the named attribute from an object. | delattr(obj, "x") | Object |
| dict() | dict(**kwargs) | Creates a new dictionary. | dict(a=1, b=2) # {"a": 1, "b": 2} | Type |
| dir() | dir([object]) | Lists names in current scope or attributes of an object. | dir([]) # list methods | Inspect |
| divmod() | divmod(a, b) | Returns quotient and remainder as a tuple. | divmod(17, 5) # (3, 2) | Math |
| enumerate() | enumerate(iterable, start=0) | Returns an enumerate object yielding (index, value) pairs. | list(enumerate("ab")) # [(0,"a"),(1,"b")] | Iterable |
| eval() | eval(expression) | Evaluates a Python expression string and returns the result. | eval("2 + 3") # 5 | Code |
Page 1 of 4
String Methods (40+)
Python String Methods (40+)
47 rows
| Method | Description | Example | Category |
|---|---|---|---|
| capitalize() | Returns string with first character capitalized and rest lowercased. | "hello world".capitalize() # "Hello world" | Case |
| casefold() | Aggressive lowercase for caseless matching. Handles Unicode edge cases. | "Straße".casefold() # "strasse" | Case |
| center() | Returns string centered in a field of given width. | "hi".center(10, "-") # "----hi----" | Align |
| count() | Returns count of non-overlapping occurrences of substring. | "banana".count("a") # 3 | Search |
| encode() | Encodes the string using the specified encoding (default UTF-8). | "hello".encode("utf-8") # b"hello" | Encode |
| endswith() | Returns True if string ends with the specified suffix. | "hello.py".endswith(".py") # True | Search |
| expandtabs() | Returns string with tab characters replaced by spaces. | "a\tb".expandtabs(4) # "a b" | Format |
| find() | Returns lowest index of substring, or -1 if not found. | "hello".find("ll") # 2 | Search |
| format() | Performs string formatting with placeholders. | "{} is {}".format("sky", "blue") | Format |
| format_map() | Like format() but uses a mapping directly. | "{name}".format_map({"name": "Bob"}) | Format |
| index() | Like find() but raises ValueError if not found. | "hello".index("ll") # 2 | Search |
| isalnum() | Returns True if all characters are alphanumeric. | "abc123".isalnum() # True | Test |
| isalpha() | Returns True if all characters are alphabetic. | "hello".isalpha() # True | Test |
| isascii() | Returns True if all characters are ASCII (Python 3.7+). | "hello".isascii() # True | Test |
| isdecimal() | Returns True if all characters are decimal characters. | "123".isdecimal() # True | Test |
| isdigit() | Returns True if all characters are digits. | "123".isdigit() # True | Test |
| isidentifier() | Returns True if string is a valid Python identifier. | "my_var".isidentifier() # True | Test |
| islower() | Returns True if all cased characters are lowercase. | "hello".islower() # True | Test |
| isnumeric() | Returns True if all characters are numeric (includes fractions, subscripts). | "\u00b2".isnumeric() # True | Test |
| isprintable() | Returns True if all characters are printable. | "hello".isprintable() # True | Test |
Page 1 of 3
List Methods
Python List Methods
11 rows
| Method | Description | Example | Mutates | Time |
|---|---|---|---|---|
| append() | Adds an element to the end of the list. | [1,2].append(3) # [1,2,3] | Yes | O(1) |
| extend() | Extends list by appending elements from an iterable. | [1,2].extend([3,4]) # [1,2,3,4] | Yes | O(k) |
| insert() | Inserts element at the specified position. | [1,3].insert(1, 2) # [1,2,3] | Yes | O(n) |
| remove() | Removes the first occurrence of the value. Raises ValueError if not found. | [1,2,3].remove(2) # [1,3] | Yes | O(n) |
| pop() | Removes and returns element at index (default last). | [1,2,3].pop() # 3, list=[1,2] | Yes | O(1) last, O(n) other |
| clear() | Removes all items from the list. | [1,2,3].clear() # [] | Yes | O(1) |
| index() | Returns index of first occurrence. Raises ValueError if not found. | [1,2,3].index(2) # 1 | No | O(n) |
| count() | Returns number of occurrences of value. | [1,2,2,3].count(2) # 2 | No | O(n) |
| sort() | Sorts list in place. key= for custom sort, reverse= for order. | [3,1,2].sort() # [1,2,3] | Yes | O(n log n) |
| reverse() | Reverses the list in place. | [1,2,3].reverse() # [3,2,1] | Yes | O(n) |
| copy() | Returns a shallow copy of the list. | b = [1,2,3].copy() | No | O(n) |
Dict Methods
Python Dict Methods
13 rows
| Method | Description | Example | Mutates |
|---|---|---|---|
| get() | Returns value for key, or default if key not found. | d.get("x", 0) # 0 if missing | No |
| keys() | Returns a view of all keys. | list(d.keys()) | No |
| values() | Returns a view of all values. | list(d.values()) | No |
| items() | Returns a view of all (key, value) pairs. | for k, v in d.items(): ... | No |
| update() | Updates dict with key-value pairs from another dict or kwargs. | d.update({"a": 1}) | Yes |
| pop() | Removes and returns value for key. Raises KeyError if missing without default. | d.pop("x", None) | Yes |
| popitem() | Removes and returns the last inserted (key, value) pair. | d.popitem() | Yes |
| setdefault() | Returns value for key if present, otherwise inserts key with default. | d.setdefault("x", []).append(1) | Conditional |
| clear() | Removes all items from the dictionary. | d.clear() | Yes |
| copy() | Returns a shallow copy of the dictionary. | new_d = d.copy() | No |
| fromkeys() | Creates a new dict with keys from iterable and values set to default. | dict.fromkeys(["a","b"], 0) | No |
| | (merge) | Merge operator (Python 3.9+). Returns new merged dict. | d1 | d2 | No |
| |= (update) | Update operator (Python 3.9+). Updates dict in place. | d1 |= d2 | Yes |
Part 12: Python 3.x Changelog
A comprehensive timeline of every Python 3.x release, from the breaking changes of 3.0 through the free-threaded GIL-optional builds of 3.13 to the template strings of 3.14.
Python 3.x Release History
15 rows
| Version | Year | Key Features | Breaking Changes |
|---|---|---|---|
| 3.0 | 2008 | Print function, Unicode strings default, integer division returns float, new I/O library | Broke backward compatibility with Python 2 |
| 3.1 | 2009 | OrderedDict, io module improvements, unittest updates | None |
| 3.2 | 2011 | argparse, concurrent.futures, __pycache__ directories, PEP 3147 .pyc files | None |
| 3.3 | 2012 | yield from, venv module, namespace packages, faulthandler, ipaddress, lzma | None |
| 3.4 | 2014 | asyncio, enum, pathlib, statistics, tracemalloc, pip bundled | None |
| 3.5 | 2015 | async/await syntax, type hints (PEP 484), unpacking generalizations (PEP 448), matrix multiplication operator (@) | None |
| 3.6 | 2016 | f-strings, variable annotations, underscores in numeric literals, async generators, dict preserves insertion order (CPython) | None |
| 3.7 | 2018 | dataclasses, dict order guaranteed by spec, breakpoint(), asyncio.run(), importlib.resources | async/await become reserved words |
| 3.8 | 2019 | Walrus operator (:=), positional-only parameters (/), f-string debugging (=), typing.TypedDict, functools.cached_property | Minor: collections.abc move |
| 3.9 | 2020 | Dict merge/update operators (|, |=), str.removeprefix/removesuffix, type hinting generics in standard collections (list[int] instead of List[int]), zoneinfo | Parser rewritten to PEG |
| 3.10 | 2021 | Structural pattern matching (match/case), parenthesized context managers, better error messages, typing.TypeAlias, zip(strict=True) | None |
| 3.11 | 2022 | 10-60% faster (Faster CPython project), exception groups (ExceptionGroup), fine-grained error locations in tracebacks, tomllib, TaskGroup | Minor deprecations |
| 3.12 | 2023 | Per-interpreter GIL (PEP 684), type parameter syntax (PEP 695), f-string improvements, improved error messages, pathlib.Path.walk() | distutils removed |
| 3.13 | 2024 | Free-threaded CPython (experimental, PEP 703), JIT compiler (experimental), improved REPL, deprecation warnings for type aliases | GIL optional build |
| 3.14 | 2025 | Template strings (PEP 750), deferred evaluation of annotations (PEP 649/749), dead battery removal (telnetlib, cgi, etc.) | Legacy modules removed |
Python Version Adoption (2019-2026)
Source: OnlineTools4Free Research
Glossary (60+ Terms)
A comprehensive glossary of Python terminology covering implementations, syntax, OOP, concurrency, iterators, typing, standard library, packaging, frameworks, and tooling.
CPython
ImplementationsThe reference and most widely used implementation of Python, written in C. When people say "Python," they usually mean CPython. Other implementations include PyPy (JIT-compiled), Jython (Java), IronPython (.NET), and GraalPython (GraalVM). CPython compiles Python source to bytecode (.pyc files) and executes it on a virtual machine.
GIL (Global Interpreter Lock)
ConcurrencyA mutex in CPython that allows only one thread to execute Python bytecode at a time. This makes CPython thread-safe but prevents true parallelism in CPU-bound multi-threaded code. The GIL is released during I/O operations. Python 3.13 introduced an experimental free-threaded mode (PEP 703) that removes the GIL. For CPU parallelism, use multiprocessing or C extensions.
PEP (Python Enhancement Proposal)
CommunityA design document providing information or describing a new feature for Python. PEPs are the primary mechanism for proposing major changes. Notable PEPs: PEP 8 (style guide), PEP 20 (Zen of Python), PEP 484 (type hints), PEP 572 (walrus operator), PEP 703 (free-threaded CPython). PEPs go through draft, accepted, final, or rejected stages.
Zen of Python
PhilosophyA collection of 19 guiding aphorisms for writing Python code (PEP 20). Accessed by typing "import this" in the interpreter. Key principles: "Beautiful is better than ugly," "Explicit is better than implicit," "Simple is better than complex," "Readability counts." These principles influence Python language design and community coding standards.
f-string
SyntaxFormatted string literal (Python 3.6+). Prefix a string with f to embed expressions inside curly braces: f"The answer is {2+2}". Supports format specifiers (f"{pi:.2f}"), expressions, method calls, and debugging syntax (f"{expr=}" shows both expression and value). Faster than str.format() and % formatting. Python 3.12 removed limitations on nested quotes.
List Comprehension
SyntaxA concise way to create lists using a single expression: [x**2 for x in range(10) if x % 2 == 0]. Equivalent to a for loop with append but more Pythonic and often faster. Can be nested. Similar syntax exists for dict comprehensions ({k: v for ...}), set comprehensions ({x for ...}), and generator expressions ((x for ...)).
Generator
IteratorsA function that uses yield to produce a sequence of values lazily, one at a time, instead of building a complete list in memory. Generators maintain their state between calls. Created with yield in a function body or with generator expressions (x for x in range(n)). Essential for processing large datasets, infinite sequences, and pipeline patterns.
Decorator
FunctionsA function that takes another function and extends its behavior without modifying it. Applied with @decorator syntax above a function or class definition. Common decorators: @property, @staticmethod, @classmethod, @functools.wraps, @functools.lru_cache. Decorators are higher-order functions that enable aspect-oriented programming patterns like logging, timing, caching, and access control.
Context Manager
Resource ManagementAn object that defines __enter__ and __exit__ methods for use with the with statement. Guarantees cleanup code runs even if exceptions occur. Common uses: file handling (open()), database connections, locks, temporary directories. The contextlib module provides @contextmanager decorator for creating context managers from generators.
Dunder Method (Magic Method)
OOPSpecial methods with double underscores (double-underscore = dunder) like __init__, __str__, __repr__, __len__, __getitem__, __eq__. They define how objects interact with built-in operations and syntax. For example, __add__ enables the + operator, __iter__ makes an object iterable, and __call__ makes an object callable like a function.
Type Hint
TypingAnnotations that specify expected types for function parameters and return values (PEP 484, Python 3.5+). Example: def greet(name: str) -> str. Type hints are not enforced at runtime by default but are used by static type checkers (mypy, pyright, pytype). Python 3.9+ allows generic types in standard collections (list[int] instead of typing.List[int]).
Dataclass
OOPA decorator (Python 3.7+) that automatically generates __init__, __repr__, __eq__, and optionally __hash__, __order__, and __post_init__ methods based on class annotations. @dataclass class Point: x: float; y: float creates a fully functional class with less boilerplate. Supports default values, field metadata, frozen (immutable) instances, and slots.
Walrus Operator
SyntaxThe assignment expression operator := (PEP 572, Python 3.8+). Assigns a value to a variable as part of an expression. Example: if (n := len(data)) > 10: print(f"too long: {n}"). Useful in while loops (while chunk := file.read(8192)), list comprehensions, and conditional expressions where you need to both test and capture a value.
Structural Pattern Matching
SyntaxThe match/case statement (PEP 634, Python 3.10+). Similar to switch/case but far more powerful: matches against patterns including literals, sequences, mappings, classes, wildcards, guards, and nested patterns. Example: match command: case ("quit",): ...; case ("go", direction): ...; case _: ... The underscore _ is the wildcard pattern.
Virtual Environment
PackagingAn isolated Python environment with its own interpreter and installed packages. Created with python -m venv myenv. Prevents dependency conflicts between projects. The venv module is built-in since Python 3.3. Third-party alternatives include virtualenv (more features), conda (cross-language), and Poetry/PDM/uv (integrated package management).
pip
PackagingThe standard package installer for Python. Installs packages from PyPI (Python Package Index). Commands: pip install package, pip install -r requirements.txt, pip freeze. Supports version pinning (package==1.2.3), extras (package[extra]), and constraints files. Being gradually superseded by uv for speed.
Poetry
PackagingA modern Python dependency management and packaging tool. Uses pyproject.toml for project metadata and poetry.lock for reproducible installs. Features: dependency resolution, virtual environment management, build/publish workflow, script definitions. Alternative to pip + setuptools + requirements.txt.
uv
PackagingAn extremely fast Python package installer and resolver written in Rust by Astral (creators of Ruff). Drop-in replacement for pip and pip-tools. 10-100x faster than pip. Supports lockfiles, virtual environments (uv venv), pip-compatible CLI, and tool management (uvx). Rapidly gaining adoption since its 2024 release.
asyncio
ConcurrencyPython standard library module for writing concurrent code using async/await syntax. Provides an event loop, coroutines, tasks, futures, synchronization primitives, and network I/O. Central to modern async Python frameworks (FastAPI, Starlette, aiohttp). asyncio.run() is the standard entry point. TaskGroup (3.11+) provides structured concurrency.
Coroutine
ConcurrencyA function defined with async def that can be suspended and resumed. When called, returns a coroutine object that must be awaited. Coroutines can use await to pause execution until an awaitable completes, yield control back to the event loop, and allow other coroutines to run. Foundation of asyncio-based concurrency.
Iterator Protocol
IteratorsAn object that implements __iter__ (returns self) and __next__ (returns next value or raises StopIteration). Any object implementing this protocol can be used in for loops, unpacking, and anywhere an iterable is expected. Generators automatically implement the iterator protocol. The iter() and next() built-in functions invoke these methods.
Iterable
IteratorsAny object that can return an iterator via its __iter__ method. Lists, tuples, strings, dicts, sets, files, generators, and ranges are all iterables. An iterable can be used in for loops, comprehensions, unpacking, and functions like map(), filter(), sorted(). Not all iterables are iterators (lists are iterable but not iterators).
Metaclass
OOPA class whose instances are classes. The default metaclass is type. Metaclasses control class creation and can modify class attributes, methods, and behavior. Defined with class MyClass(metaclass=MyMeta). Used in ORMs (Django models), ABCs, and frameworks. Most Python developers never need to write metaclasses directly.
ABC (Abstract Base Class)
OOPA class from the abc module that cannot be instantiated and defines abstract methods that subclasses must implement. Created with class MyABC(ABC) and @abstractmethod. ABCs enforce interfaces in Python. The collections.abc module provides ABCs for containers (Iterable, Sequence, Mapping, etc.).
Descriptor
OOPAn object attribute with binding behavior, implementing __get__, __set__, and/or __delete__. Descriptors power properties, methods, classmethod, staticmethod, and __slots__. When accessed on an instance, the descriptor protocol is invoked. Data descriptors (with __set__ or __delete__) take priority over instance dictionaries.
Slot
OOPUsing __slots__ in a class to declare a fixed set of instance attributes, preventing __dict__ creation. Reduces memory usage (significant for many instances) and slightly speeds up attribute access. Example: class Point: __slots__ = ("x", "y"). Trade-off: no dynamic attributes, complex with inheritance.
GC (Garbage Collector)
MemoryPython uses reference counting as its primary memory management strategy. When an object reference count drops to zero, it is immediately deallocated. The gc module provides a cyclic garbage collector that detects reference cycles (objects referencing each other) that reference counting alone cannot handle. gc.collect() forces a collection cycle.
MRO (Method Resolution Order)
OOPThe order in which Python searches for methods in a class hierarchy. Uses the C3 linearization algorithm. For single inheritance, it is straightforward (child -> parent). For multiple inheritance, C3 ensures a consistent, predictable order. Inspect with ClassName.__mro__ or ClassName.mro(). super() follows the MRO.
Mixin
OOPA class designed to provide additional functionality to other classes through multiple inheritance, without being instantiated on its own. Mixins add specific behavior (like serialization, logging, or comparison methods) to classes. Example: class LoggingMixin: def log(self): print(f"{self.__class__.__name__}: {self}").
Protocol (Structural Typing)
TypingA typing construct (PEP 544, Python 3.8+) for structural subtyping (duck typing in the type system). A class satisfies a Protocol if it has the required attributes and methods, without explicitly inheriting from it. Enables type-safe duck typing: class Drawable(Protocol): def draw(self) -> None: ...
TypeVar
TypingA type variable used for generic type hints. T = TypeVar("T") creates a type variable. Used in generic functions: def first(items: list[T]) -> T. Supports bounds (TypeVar("T", bound=Comparable)), constraints (TypeVar("T", int, str)), and variance (covariant, contravariant). Python 3.12 introduced simpler syntax: def first[T](items: list[T]) -> T.
Union Type
TypingA type hint indicating a value can be one of several types. Old syntax: Union[int, str]. New syntax (3.10+): int | str. Optional[X] is shorthand for X | None. Union types are commonly used for function parameters that accept multiple types and return values that might be None.
Unpacking
SyntaxExtracting values from iterables (sequences, dicts) into individual variables. Tuple unpacking: a, b = 1, 2. Extended unpacking: first, *rest = [1, 2, 3, 4]. Dict unpacking: {**d1, **d2}. Function argument unpacking: fn(*args, **kwargs). Swap idiom: a, b = b, a.
Comprehension
SyntaxA concise syntax for creating collections from iterables. List: [x*2 for x in range(5)]. Dict: {k: v for k, v in items}. Set: {x for x in range(5)}. Generator expression: (x for x in range(5)). Comprehensions can include conditions (if) and be nested. More readable and often faster than equivalent loops.
Lambda
FunctionsAn anonymous, single-expression function. Syntax: lambda args: expression. Example: sorted(data, key=lambda x: x.name). Lambdas are limited to a single expression (no statements, no assignments). Used for short callback functions, sort keys, and filter predicates. For anything more complex, use a named function.
Closure
FunctionsA function object that has access to variables in its enclosing scope, even after the outer function has finished executing. Closures are created when a nested function references variables from the enclosing function. The nonlocal keyword allows modifying enclosed variables. Used for factory functions, decorators, and callback patterns.
args and kwargs
Functions*args collects positional arguments into a tuple. **kwargs collects keyword arguments into a dictionary. Used in function definitions to accept variable numbers of arguments. Convention: *args, **kwargs (any names work but these are standard). Also used for argument unpacking in function calls: fn(*list_of_args, **dict_of_kwargs).
Pathlib
Standard LibraryObject-oriented filesystem path library (Python 3.4+). Path objects represent filesystem paths with intuitive operators: Path("a") / "b" / "c.txt". Methods: .read_text(), .write_text(), .exists(), .is_file(), .glob(), .mkdir(), .stat(). Preferred over os.path for new code. Path.walk() added in Python 3.12.
collections.defaultdict
Standard LibraryA dict subclass that calls a factory function to provide default values for missing keys. defaultdict(list) creates empty lists for new keys; defaultdict(int) creates 0 for new keys. Eliminates the need for checking key existence before appending or incrementing. More efficient than dict.setdefault().
collections.Counter
Standard LibraryA dict subclass for counting hashable objects. Counter("abracadabra") returns Counter({"a": 5, "b": 2, "r": 2, "c": 1, "d": 1}). Supports arithmetic (addition, subtraction of counters), most_common(n), and set-like operations (intersection, union). Ideal for frequency analysis and histogram creation.
collections.namedtuple
Standard LibraryA factory function for creating tuple subclasses with named fields. Point = namedtuple("Point", ["x", "y"]). Instances are immutable, memory-efficient, and support both index and attribute access: p.x == p[0]. Being gradually replaced by dataclasses for new code, but still useful for simple, immutable data structures.
itertools
Standard LibraryStandard library module providing fast, memory-efficient iterator building blocks. Key functions: chain (concatenate iterables), product (Cartesian product), permutations, combinations, groupby, islice, count, cycle, repeat, starmap, accumulate, zip_longest. Essential for data processing pipelines and combinatorial algorithms.
functools
Standard LibraryStandard library module for higher-order functions and operations on callable objects. Key tools: @lru_cache/@cache (memoization), @wraps (preserve function metadata in decorators), partial (partial function application), reduce (fold operation), @singledispatch (single-dispatch generic functions), @cached_property.
contextlib
Standard LibraryStandard library module providing utilities for common context manager patterns. @contextmanager creates context managers from generators. suppress() ignores specified exceptions. redirect_stdout/stderr() redirects output. ExitStack manages multiple context managers dynamically. nullcontext() provides a no-op context manager.
PyPI (Python Package Index)
PackagingThe official third-party software repository for Python. Hosts over 500,000 packages. Packages are installed via pip install package_name. Package authors upload distributions using twine or build tools. URL: pypi.org. PyPI supports binary wheels for faster installation and sdist (source distributions) for building from source.
Wheel
PackagingA built distribution format for Python packages (.whl files). Wheels are pre-built and install faster than source distributions because they skip the build step. Naming convention includes Python version, ABI, and platform tags. PEP 427 defines the format. pip prefers wheels when available. Build with python -m build.
pyproject.toml
PackagingThe standard configuration file for Python projects (PEP 518, PEP 621). Replaces setup.py, setup.cfg, and tool-specific config files. Defines build system, project metadata, dependencies, and tool settings (pytest, mypy, ruff, black). All modern build tools (setuptools, poetry, hatch, pdm, flit, maturin) support it.
Ruff
ToolingAn extremely fast Python linter and formatter written in Rust. 10-100x faster than flake8, pylint, isort, and black combined. Implements 800+ lint rules including pyflakes, pycodestyle, isort, pydocstyle, and more. Includes a built-in formatter (replacement for Black). Rapidly becoming the standard Python linting tool.
mypy
ToolingThe original static type checker for Python. Analyzes type annotations to find bugs before runtime. Supports gradual typing (mix typed and untyped code), generics, protocols, TypedDict, and plugin architecture. Alternatives: pyright (Microsoft, faster), pytype (Google), pyre (Meta). Running mypy in CI catches type errors early.
FastAPI
FrameworksA modern, high-performance web framework for building APIs with Python 3.7+ based on type hints. Uses Starlette for HTTP and Pydantic for data validation. Features: automatic OpenAPI docs, dependency injection, async support, WebSocket support, OAuth2/JWT integration. Fastest-growing Python web framework in 2023-2026.
Django
FrameworksA high-level, batteries-included web framework following the model-template-view (MTV) pattern. Includes ORM, admin interface, authentication, URL routing, template engine, and form handling. Powers Instagram, Pinterest, Mozilla, and thousands of other sites. Django 5.x added generics-based views, async ORM support, and database-generated fields.
Pydantic
LibrariesA data validation library using Python type annotations. Pydantic v2 (rewritten in Rust) is 5-50x faster than v1. Defines data models as classes with type-annotated fields. Provides automatic validation, serialization, JSON Schema generation, and settings management. Foundation of FastAPI request/response handling.
pytest
TestingThe most popular Python testing framework. Uses plain assert statements instead of special assertion methods. Features: fixtures (dependency injection for tests), parametrize (test multiple inputs), markers (categorize tests), plugins (1000+ available). Simpler and more powerful than the built-in unittest module.
NumPy
Data ScienceThe fundamental package for scientific computing in Python. Provides n-dimensional arrays (ndarray), mathematical functions, linear algebra, Fourier transforms, and random number generation. NumPy arrays are stored in contiguous memory and operations are vectorized (implemented in C), making them 10-100x faster than Python lists for numerical operations.
Pandas
Data ScienceA data analysis and manipulation library built on NumPy. Provides DataFrame (2D labeled data) and Series (1D labeled data) objects. Features: data loading (CSV, Excel, SQL, JSON), filtering, grouping, pivoting, merging, time series analysis, and missing data handling. The standard tool for data wrangling in Python.
Exception Handling
Error HandlingPython uses try/except/else/finally blocks for error handling. try contains code that might raise an exception. except catches specific exceptions. else runs if no exception occurred. finally always runs (cleanup). Python 3.11 added ExceptionGroup for handling multiple simultaneous exceptions, and except* for catching exception groups.
with Statement
Resource ManagementA control flow statement for wrapping code blocks with context manager methods (__enter__/__exit__). Guarantees cleanup even if exceptions occur. Common: with open("file.txt") as f: data = f.read(). Python 3.10 allows parenthesized multi-line context managers. Python 3.13 supports using (await using) for async resource management.
Property
OOPA way to define managed attributes in Python classes using the @property decorator. Allows getter, setter, and deleter methods that look like simple attribute access. class Circle: @property def area(self): return math.pi * self.radius**2. Properties enforce encapsulation while maintaining a clean API.
Class Method vs Static Method
OOP@classmethod receives the class as its first argument (cls) and can access/modify class state. Used for alternative constructors (e.g., from_json, from_dict). @staticmethod receives no implicit first argument and is just a function scoped to the class namespace. Use when the method does not need access to instance or class state.
Multiple Inheritance
OOPPython supports inheriting from multiple parent classes: class Child(Parent1, Parent2). Method resolution follows the C3 linearization algorithm (MRO). Python avoids the diamond problem through MRO. Common pattern: mixins add specific capabilities without being standalone classes. Overuse leads to complexity; prefer composition over inheritance.
Enum
Standard LibraryThe enum module (Python 3.4+) provides support for enumerations: class Color(Enum): RED = 1; GREEN = 2; BLUE = 3. Enums are iterable, comparable, hashable, and prevent duplicate values. IntEnum allows integer comparison. StrEnum (3.11+) allows string operations. Flag supports bitwise operations for permissions/options.
FAQ (20 Questions)
Try It Yourself
Use these embedded tools to practice with data formats and patterns discussed in this guide.
Try it yourself
Json Formatter
Try it yourself
Regex Tester
Raw Data Downloads
All datasets from this report are available for download in CSV format under a Creative Commons Attribution 4.0 license.
Citations and Sources
Try These Tools for Free
Put this knowledge into practice with our browser-based tools. No signup needed.
JSON Formatter
Format, validate, and beautify JSON data with syntax highlighting.
Regex Tester
Test and debug regular expressions with real-time matching and explanations.
CSV to JSON
Convert CSV data to JSON and JSON to CSV format online.
JSON to Python
Paste JSON and generate Python dataclass or TypedDict definitions with nested type support.
Hash Generator
Generate MD5, SHA-1, SHA-256, and SHA-512 hashes from text or files.
String Utils
Reverse, shuffle, sort lines, remove duplicates, and more text operations.
Related Research Reports
The Complete Machine Learning Guide 2026: Supervised, Unsupervised, Neural Networks & MLOps
The definitive machine learning reference for 2026. Covers supervised learning, unsupervised learning, neural networks, deep learning, evaluation metrics, feature engineering, and MLOps. 28,000+ words.
The Complete Data Structures & Algorithms Guide 2026: Arrays, Trees, Graphs, Hash Tables & Big-O
The definitive data structures reference for 2026. Covers arrays, linked lists, stacks, queues, trees, graphs, hash tables, heaps, tries, sorting algorithms, and Big-O complexity analysis. 28,000+ words.
The Complete Guide to AI & Machine Learning Tools 2026: LLMs, RAG, Agents & Beyond
The definitive guide to AI and ML tools in 2026. Covers LLMs, prompt engineering, fine-tuning, RAG, embeddings, vector databases, AI agents, multimodal AI, AI coding assistants, image generation, AI audio, and ethical AI. 15+ model comparisons, 30+ tool reviews. 32,000+ words.
