🎁 New User? Get 20% off your first purchase with code NEWUSER20 Register Now →
Menu

Categories

Python Advanced

What is Slots?

A class mechanism that restricts attribute creation and reduces memory usage by using a fixed set of instance variables.

By default, Python objects store attributes in a __dict__ dictionary. __slots__ replaces this with a fixed tuple of allowed attributes: class Point: __slots__ = ('x', 'y'). This prevents adding arbitrary attributes and significantly reduces memory per instance.

Benefits include 30-40% memory reduction for classes with many instances, faster attribute access, and preventing typos in attribute names. Trade-offs include no __dict__, no multiple inheritance with different __slots__, and no dynamic attributes.

Related Terms

Python Context Variable
A variable that maintains separate values for each execution context, enabling implicit state passing in async code without global variables.
GIL (Global Interpreter Lock)
A mutex in CPython that allows only one thread to execute Python bytecode at a time, limiting true parallelism.
Walrus Operator
The := operator that assigns a value to a variable as part of an expression, introduced in Python 3.8.
List Comprehension
A concise syntax for creating new lists by applying an expression to each item in an existing iterable.
Poetry
A modern Python dependency management and packaging tool that handles virtual environments, locking, and publishing.
Enum
A built-in class for creating enumerated constants — named groups of related values that improve code readability.
View All Python Terms →