1. Home
  2. Blog
  3. Software Development

Software Development

Python __slots__ Explained: Memory Savings, Speed and 6 Traps, Tested

Python slots replace the per-object attribute dictionary with a fixed set of fields. Older articles promise big memory and speed wins, but CPython has changed. We measured a million objects on Python 3.13: memory dropped by up to 41 percent, attribute speed did not change at all, and six traps can break your code if you add slots without thinking.

9 min read
Python __slots__ explained: memory savings, speed and 6 traps, tested

Key takeaways

  • Python slots (__slots__) store attributes in fixed positions instead of a per-instance dictionary.
  • One million two-attribute objects used 96.4 MB normally and 56.4 MB with slots, a 41 percent saving, on Python 3.13.6.
  • Reading and writing attributes took the same time with or without slots (about 12 ns), and creating slotted objects was actually slower in our run.
  • Slots block new attributes, weak references and cached_property, and a subclass without its own __slots__ silently gets a dictionary back.

Every normal Python object can grow new attributes at any time, because its attributes live in a dictionary. That flexibility costs memory, and when you create millions of small objects (points, records, graph nodes, parsed rows) the cost adds up. Python slots trade flexibility for a fixed layout: you declare the attribute names up front, and Python reserves exactly that much space.

Many tutorials still quote numbers from Python 3.6-era benchmarks. We re-measured everything on Python 3.13.6 using tracemalloc for memory and timeit for speed (best of five runs), and the results are more nuanced.

What __slots__ does

Without slots, each instance carries space for a __dict__ that maps attribute names to values. With __slots__, the class creates a descriptor for each listed name, and each instance stores values in a small fixed array. We confirmed it: a slotted object had no __dict__ attribute at all, and S.x on the class printed <member 'x' of 'S' objects>, which is that descriptor.

The syntax

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class SlotPoint:
    __slots__ = ("x", "y")
    def __init__(self, x, y):
        self.x = x
        self.y = y

__slots__ is a class attribute containing the allowed attribute names, usually a tuple of strings. Nothing else about the class changes: methods, properties and class methods work as before.

Memory, measured

Objects Normal class With __slots__ Saving
1,000,000 objects, 2 attributes set to None 96.4 MB 56.4 MB 41%
1,000,000 objects, 2 integer attributes 128.4 MB 88.4 MB 31%
200,000 objects, 10 attributes 33.6 MB 24.0 MB 29%

Slots saved about 40 bytes per object in every test. The percentage depends on what else you store: with integer attributes, the integer objects themselves (which slots do not shrink) take a share of the total, so the relative saving falls to 31 percent. For workloads with millions of small objects, saving tens of megabytes is still worthwhile. Beware of claims of 50 to 70 percent; those came from older Python versions with larger per-instance dictionaries.

Speed, measured

Operation Normal Slots
Read obj.x 12.0 ns 11.9 ns
Write obj.x = 5 12.8 ns 12.6 ns
Create an instance 85.1 ns 123.5 ns

Attribute access was identical within measurement noise. Creating slotted instances was slower in our run, which surprised us; we repeated it with the same result, though the exact gap may differ on other machines and versions. The practical conclusion is clear: do not add slots for speed. Add them for memory, or to stop accidental new attributes.

Why the gains shrank in modern Python

Recent CPython versions store the attributes of ordinary objects inline and only build a real dictionary when code asks for __dict__. Our test showed this directly: after we simply read p.__dict__ once, writing an attribute on that normal object slowed from 12.8 ns to 28.4 ns, because a full dictionary now existed. Slots still avoid the space that layout needs, but normal objects are far cheaper than they used to be, so the gap is smaller than older benchmarks suggest.

Slots with dataclasses

from dataclasses import dataclass

@dataclass(slots=True)
class D:
    x: int
    y: int
# 1,000,000 instances: 88.4 MB, the same as the hand-written slotted class

Since Python 3.10, @dataclass(slots=True) generates __slots__ from the field list, so you get the memory saving without repeating names. It is the easiest way to use slots for data-holding classes; see our Python dataclasses guide for the rest of the dataclass options.

Trap 1: you cannot add new attributes

s = SlotPoint(1, 2)
s.z = 3
# AttributeError: 'SlotPoint' object has no attribute 'z'
#   and no __dict__ for setting new attributes

This is a feature when it catches typos like self.vlaue = 1, and a problem when libraries or tests attach extra attributes to your objects (some mocking and serialisation tools do). The normal class happily accepted p.z = 3.

Trap 2: inheritance can silently undo slots

class Child(SlotPoint):
    pass
c = Child(1, 2); c.z = 9
hasattr(c, "__dict__"), c.__dict__     # True {'z': 9}

class Child2(SlotPoint):
    __slots__ = ("z",)
hasattr(Child2(1, 2), "__dict__")       # False

A subclass that does not declare its own __slots__ gets a normal dictionary again, and the memory saving disappears without any warning. Every class in the hierarchy needs __slots__, listing only the new names (repeating the parent’s names wastes space). Inheritance rules in general are covered in our classes and objects guide.

Trap 3: weak references stop working

weakref.ref(SlotPoint(1, 2))
# TypeError: cannot create weak reference to 'SlotPoint' object

class W:
    __slots__ = ("x", "__weakref__")
weakref.ref(W())    # works

Caches, observer patterns and some frameworks rely on weak references. Add "__weakref__" to the slots if you need them.

Trap 4: class-level defaults clash with slots

class Bad:
    __slots__ = ("x",)
    x = 5
# ValueError: 'x' in __slots__ conflicts with class variable

You cannot give a slot a default by assigning it in the class body, because the slot descriptor and the class variable would use the same name. Set defaults in __init__ instead, or use a dataclass with slots=True, which handles field defaults for you.

Trap 5: functools.cached_property fails

class CP:
    __slots__ = ("x",)
    @cached_property
    def big(self): return 1

CP().big
# TypeError: No '__dict__' attribute on 'CP' instance to cache 'big' property.

cached_property stores its result in the instance dictionary, which slotted objects do not have. Use a plain property with a dedicated slot for the cached value, or functools.lru_cache on a method, as described in our functools guide.

Trap 6: vars() and __dict__-based tools break

vars(p)    # {'x': 5, 'y': 2, 'z': 3}
vars(s)    # TypeError: vars() argument must have __dict__ attribute

class Both:
    __slots__ = ("x", "__dict__")   # escape hatch
b = Both(); b.x = 1; b.y = 2
b.__dict__   # {'y': 2}

Code that serialises objects with vars(obj) or obj.__dict__ fails on slotted classes. Pickling still worked in our test (pickle.loads(pickle.dumps(s)).x returned the right value), but custom JSON encoders often need updating. Adding "__dict__" to the slots restores dynamic attributes for names outside the list, at the cost of most of the saving.

When to use __slots__

  • Use them for classes with millions of instances and a fixed set of fields: points, tokens, tree nodes, records from a large file.
  • Use them when you want to forbid accidental attributes on value objects.
  • Prefer @dataclass(slots=True) for new data classes; it is less error-prone than writing slots by hand.
  • Skip them for classes with only a few hundred instances, for classes used with frameworks that add attributes, and when you need cached_property.
  • Measure first. Use tracemalloc on your real data; for many programs a different data structure, such as tuples, NumPy arrays or columns in a dataframe, saves far more.

Type checkers understand slotted classes normally, so type hints need no changes.

Measuring the saving on your own classes

import tracemalloc

def mem(cls, n=1_000_000):
    tracemalloc.start()
    objs = [cls(None, None) for _ in range(n)]
    current, _ = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return current / 1e6

mem(Point), mem(SlotPoint)     # 96.4 MB vs 56.4 MB in our run

This is the exact helper behind our memory table. tracemalloc counts every allocation Python makes while the objects are created, so it includes the objects, their attribute storage and the list holding them. Keep a reference to the objects (here the objs list) until you read the number, or they are freed before you measure. sys.getsizeof is not a good substitute: it reports only the shallow size of one object, and in our run it returned 48 bytes for both a normal and a slotted instance, hiding the difference completely. Asking for p.__dict__ to measure it also creates the dictionary you were trying to measure, which is the same effect that slowed attribute writes in the speed test.

Run the measurement with realistic attribute values from your application, because large strings or nested objects can make the per-object overhead that slots remove a small fraction of the total.

Final thoughts

Python slots still deliver real memory savings, about 40 bytes per object and up to 41 percent in our tests, but on modern Python they do not make attribute access faster, and creating objects was slower in our run. Use them when you have many instances with fixed fields, declare them in every class of the hierarchy, add __weakref__ if needed, and avoid cached_property. For most new code, @dataclass(slots=True) gives you the benefit with the least effort.

Frequently asked questions

What does __slots__ do in Python?

It declares a fixed list of attribute names for a class. Instances store those values in a compact array instead of a per-object dictionary, which saves memory and blocks other attributes.

How much memory does __slots__ save?

In our Python 3.13 tests, about 40 bytes per object: one million small objects went from 96.4 MB to 56.4 MB. The percentage depends on what the attributes hold.

Does __slots__ make Python faster?

Not on modern Python in our tests. Attribute reads and writes took the same time, about 12 nanoseconds, and creating slotted objects was slower.

Do subclasses inherit __slots__?

They inherit the parent slots, but a subclass without its own slots declaration gets an instance dictionary again. Declare slots in every subclass, listing only the new names.

Can I use __slots__ with dataclasses?

Yes. Since Python 3.10, pass slots=True to the dataclass decorator and it generates the slots from the fields for you.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →