Nested classes
suggest changeA nested class (also called an inner class) is a class defined inside the body of another class. In Python this is purely a matter of namespacing: the nested class becomes an attribute of the outer class, nothing more.
That makes Python nested classes quite different from Java's inner classes. A nested class has no hidden reference to an instance of the outer class, and its methods can't see the outer class's attributes by bare name. Once you understand that, nested classes are a handy tool for grouping helper types with the class that uses them.
This article covers how nested classes work, the scoping rules that surprise people, common uses (helper types, enums, exceptions, Meta-style configuration), overriding nested classes in subclasses, type hints, pickling, and how to bind a nested class to an outer instance if you really need to.
Defining and using a nested class
A linked list needs a node type, but nobody outside the list cares about it. Nest it:
class LinkedList:
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __init__(self):
self.head = None
def push(self, value):
self.head = self.Node(value, self.head)
def __iter__(self):
node = self.head
while node:
yield node.value
node = node.next
lst = LinkedList()
for v in [1, 2, 3]:
lst.push(v)
print(list(lst))
n = LinkedList.Node(42)
print(n.value)
[3, 2, 1]
42
The nested class is reachable as LinkedList.Node from outside and as self.Node (or LinkedList.Node) from inside methods. It's an ordinary class: you can instantiate it, subclass it and pass it around.
Python records the nesting in __qualname__ (the qualified name), while __name__ is just the short name:
print(LinkedList.Node.__name__)
print(LinkedList.Node.__qualname__)
print(LinkedList.Node)
print(type(lst.head))
Node
LinkedList.Node
<class '__main__.LinkedList.Node'>
<class '__main__.LinkedList.Node'>
Nesting can go deeper, though more than two levels is rarely a good idea:
class A:
class B:
class C:
z = 3
print(A.B.C.__qualname__, A.B.C.z)
A.B.C 3
The class body runs once
The class statement for the nested class runs exactly once, while the outer class body executes. There is a single Node class shared by every LinkedList instance; accessing it through an instance just finds the class attribute:
class Outer:
def __init__(self, name):
self.name = name
class Inner:
pass
o = Outer("x")
i = o.Inner()
print(hasattr(i, "name"))
print(o.Inner is Outer.Inner)
False
True
o.Inner() creates an Inner that knows nothing about o. There is no implicit Outer.this like in Java.
Compare that with a class defined inside a function, which is created anew on every call (a closure over the function's locals):
def make_counter_class(start):
class Counter:
def __init__(self):
self.value = start
return Counter
A = make_counter_class(0)
B = make_counter_class(10)
print(A().value, B().value)
print(A is B, A.__qualname__)
0 10
False make_counter_class.<locals>.Counter
Local classes like this are useful for factories, but they have downsides (they can't be pickled, see below). A class nested in a class does not have these problems.
Scoping: the nested class can't see outer names
This is the most common surprise. A class body is a scope, but it is not an enclosing scope for anything defined inside it. Methods of the nested class can't refer to the outer class's attributes by bare name:
class Outer:
greeting = "hello"
class Inner:
def show(self):
return greeting
try:
Outer.Inner().show()
except NameError as e:
print("NameError:", e)
NameError: name 'greeting' is not defined
The same applies to the nested class's own body, which runs while the outer body is still executing:
try:
class Outer3:
size = 10
class Inner:
limit = size * 2
except NameError as e:
print("NameError:", e)
NameError: name 'size' is not defined
Name lookup goes local scope, then enclosing function scopes, then module globals, then builtins. Class scopes are skipped. This is the same rule described in Functions skip class scope when looking up names.
The fix is to qualify the name. Inside methods the outer class already exists, so reference it through the module-level name:
class Outer2:
greeting = "hello"
class Inner:
def show(self):
return Outer2.greeting
print(Outer2.Inner().show())
hello
In the nested class body (not in methods), even Outer3.size won't work, because the name Outer3 is only bound after the whole outer body finishes. If the nested class needs a value at definition time, define it at module level or set it after the outer class is created (Outer3.Inner.limit = Outer3.size * 2).
The reverse direction works fine: the outer class body can use the nested class by bare name, because both live in the same class scope while it executes. You'll see that in the next example.
Passing the outer instance explicitly
When a nested object needs its owner, pass it in. This is explicit and easy to follow:
class Account:
def __init__(self, owner):
self.owner = owner
self.transactions = []
class Transaction:
def __init__(self, account, amount):
self.account = account
self.amount = amount
def __repr__(self):
return f"Transaction({self.account.owner!r}, {self.amount})"
def deposit(self, amount):
t = self.Transaction(self, amount)
self.transactions.append(t)
return t
acc = Account("alice")
acc.deposit(100)
acc.deposit(-30)
print(acc.transactions)
[Transaction('alice', 100), Transaction('alice', -30)]
Note that this creates a reference cycle (account -> transactions list -> transaction -> account). That's fine; Python's garbage collector handles cycles. If the child should not keep the parent alive, store a weakref.ref(account) instead.
Use case: enums and exceptions that belong to a class
Nesting an Enum or an exception type keeps related names together and makes call sites self-documenting:
from enum import Enum
class Order:
class Status(Enum):
PENDING = "pending"
SHIPPED = "shipped"
DELIVERED = "delivered"
class InvalidTransition(Exception):
pass
_allowed = {
Status.PENDING: {Status.SHIPPED},
Status.SHIPPED: {Status.DELIVERED},
Status.DELIVERED: set(),
}
def __init__(self):
self.status = Order.Status.PENDING
def advance(self, new_status):
if new_status not in self._allowed[self.status]:
raise Order.InvalidTransition(f"{self.status.name} -> {new_status.name}")
self.status = new_status
order = Order()
order.advance(Order.Status.SHIPPED)
print(order.status)
try:
order.advance(Order.Status.PENDING)
except Order.InvalidTransition as e:
print(f"{type(e).__qualname__}: {e}")
Status.SHIPPED
Order.InvalidTransition: SHIPPED -> PENDING
_allowed refers to Status by bare name. That works because it's evaluated directly in the outer class body, where Status is a local name. It would not work inside a method, a lambda or a comprehension body in the class.
The standard library uses this pattern too, though sparingly. More often you'll find exceptions defined at module level, which is equally good; nesting is worth it when a module contains several classes that each have their own Error.
See Enum and Creating custom exception types for more on those types.
Use case: overridable helper classes
Because the outer class looks the nested class up through self, a subclass can replace it just by defining a class with the same name. This is a lightweight alternative to passing a factory around:
class Parser:
class Error(Exception):
pass
class Token:
def __init__(self, text):
self.text = text
def __repr__(self):
return f"{type(self).__name__}({self.text!r})"
def parse(self, source):
if not source:
raise self.Error("empty input")
return [self.Token(word) for word in source.split()]
class UpperParser(Parser):
class Token(Parser.Token):
def __init__(self, text):
super().__init__(text.upper())
print(Parser().parse("a b"))
print(UpperParser().parse("a b"))
try:
UpperParser().parse("")
except Parser.Error as e:
print("caught:", e)
[Token('a'), Token('b')]
[Token('A'), Token('B')]
caught: empty input
Two details matter here:
parseusesself.Token, notParser.Token. Hard-coding the outer class name would defeat overriding.UpperParser.TokensubclassesParser.Tokenexplicitly. Nested classes are not inherited in the sense of being merged; the subclass'sTokensimply shadows the parent's attribute. If you want the parent's behavior, inherit from it.
UpperParser didn't redefine Error, so self.Error finds Parser.Error through normal attribute lookup, and except Parser.Error catches it.
Use case: Meta-style configuration
Frameworks such as Django (class Meta: on models and forms) use a nested class as a declarative bag of options. The nested class is never instantiated; the outer class reads its attributes. You can implement the pattern with __init_subclass__:
class Model:
class Meta:
table = None
ordering = ()
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
meta = cls.__dict__.get("Meta")
cls._table = getattr(meta, "table", None) or cls.__name__.lower() + "s"
cls._ordering = getattr(meta, "ordering", ())
class User(Model):
class Meta:
table = "app_users"
ordering = ("-created",)
class Post(Model):
pass
print(User._table, User._ordering)
print(Post._table, Post._ordering)
app_users ('-created',)
posts ()
cls.__dict__.get("Meta") looks only at the class being defined, so Post does not pick up its parent's Meta and gets defaults instead. Using getattr(cls, "Meta") would inherit the parent's options, which is sometimes what you want.
Older Pydantic versions used the same idea (class Config:); Pydantic 2 replaced it with a model_config = ConfigDict(...) attribute, which is easier for type checkers to understand. For new code, a plain class attribute or class keyword arguments (class User(Model, table="app_users"), handled in __init_subclass__) are usually clearer than a nested options class.
Nested dataclasses
Dataclasses nest well for structured configuration. Use field(default_factory=...) so each instance gets its own sub-object:
from dataclasses import dataclass, field
@dataclass
class Config:
@dataclass
class Database:
host: str = "localhost"
port: int = 5432
@dataclass
class Cache:
ttl: int = 60
enabled: bool = True
name: str = "app"
db: Database = field(default_factory=Database)
cache: Cache = field(default_factory=Cache)
cfg = Config(db=Config.Database(port=6543))
print(cfg)
print(cfg.db.port, cfg.cache.ttl)
Config(name='app', db=Config.Database(host='localhost', port=6543), cache=Config.Cache(ttl=60, enabled=True))
6543 60
The nested classes are not fields: @dataclass only turns annotated names into fields, and Database and Cache have no annotations in the outer body. The generated __repr__ uses __qualname__, which is why it prints Config.Database(...).
Type hints
Annotations on the outer class's methods are evaluated in the outer class body, so the nested class can be named directly. Inside the nested class, though, the outer class doesn't exist yet when its methods are defined:
class Tree:
class Node:
def __init__(self, value: int, tree: "Tree") -> None:
self.value = value
self.tree = tree
def sibling(self) -> "Tree.Node":
return Tree.Node(self.value + 1, self.tree)
def root(self) -> Node: # fine: evaluated in Tree's class body
return self.Node(0, self)
print(Tree().root().sibling().value)
print(Tree.root.__annotations__)
try:
class Broken:
class Node:
def owner(self) -> Broken:
...
except NameError as e:
print("NameError:", e)
1
{'return': <class '__main__.Tree.Node'>}
NameError: name 'Broken' is not defined
Options for referring to the outer class from inside a nested one:
- quote the annotation:
"Tree","Tree.Node"(works everywhere, and type checkers understand it) - add
from __future__ import annotationsat the top of the module, which turns all annotations into strings - on Python 3.14+, annotations are evaluated lazily (PEP 649), so
-> Brokenworks without quotes
Inside Node's own methods, refer to Node itself as "Tree.Node" or use typing.Self (Python 3.11+) when you mean "an instance of this class or a subclass".
Pickling and introspection
pickle stores classes by module and qualified name, so instances of nested classes pickle fine (Python 3.4+, any protocol):
import pickle
class Outer:
class Inner:
def __init__(self, x):
self.x = x
def make():
class Local:
pass
return Local()
data = pickle.dumps(Outer.Inner(5))
print(pickle.loads(data).x)
try:
pickle.dumps(make())
except (AttributeError, pickle.PicklingError) as e:
print(type(e).__name__, e)
5
AttributeError Can't get local object 'make.<locals>.Local'
The class defined inside a function fails because make.<locals>.Local can't be found by name when unpickling. (Newer Python versions may raise PicklingError with a slightly different message, hence catching both.) This is another reason to prefer class-level nesting over local classes when objects must be serialized or sent to multiprocessing workers. See Persistence with pickle.
Nested classes are just class attributes, so introspection tools see them like any other member:
import inspect
class A:
x = 1
class B:
pass
print("B" in vars(A))
print([name for name, obj in inspect.getmembers(A, inspect.isclass) if name != "__class__"])
True
['B']
Binding a nested class to the outer instance
If you really want Java-style outer.Inner(...) that automatically receives outer, a tiny descriptor does it. A class attribute with a __get__ method controls what instance access returns:
import functools
class inner:
"""Make a nested class receive the outer instance as its first argument."""
def __init__(self, cls):
self.cls = cls
def __get__(self, instance, owner):
if instance is None:
return self.cls
return functools.partial(self.cls, instance)
class Window:
def __init__(self, title):
self.title = title
self.buttons = []
@inner
class Button:
def __init__(self, window, label):
self.window = window
self.label = label
window.buttons.append(self)
def __repr__(self):
return f"Button({self.label!r} in {self.window.title!r})"
w = Window("Settings")
w.Button("OK")
w.Button("Cancel")
print(w.buttons)
print(Window.Button)
[Button('OK' in 'Settings'), Button('Cancel' in 'Settings')]
<class '__main__.Window.Button'>
Accessed on the class, Window.Button is the plain class (useful for isinstance checks and subclassing). Accessed on an instance, it's a partial that pre-fills the window argument, exactly like a bound method pre-fills self. See Descriptors and Dotted Lookups for how __get__ works.
This is clever, and clever code has a cost: readers must know about the decorator to understand why Button gets a window argument it was never passed. The explicit self.Transaction(self, amount) style from earlier is usually the better choice.
When to nest and when not to
Nest a class when:
- it's a helper used only by the outer class (
Node,Entry,_Cursor), and you want that relationship visible - it's a closely tied type such as an
Enumof states or anErrorraised by the outer class, and the qualified name (Order.Status) reads well - subclasses should be able to swap it out via
self.Inner - it's a declarative options container that a framework expects (
Meta)
Prefer a module-level class when:
- other code uses it on its own;
from shapes import Pointis nicer thanShape.Point - it's large; a 200-line class nested inside another hurts readability, and the extra indentation adds up
- it needs to reference the outer class's attributes heavily; the scoping rules make that awkward
To mark a helper as internal without nesting, a module-level _Node with a leading underscore is the conventional Python signal. See Visibility and encapsulation.
Summary:
- a nested class is a class attribute of the outer class, created once when the outer body runs
- it has no implicit link to an outer instance; pass one explicitly if needed
- class scope is skipped by name lookup, so qualify outer names (
Outer.attr) inside nested methods - use
self.Innerin the outer class so subclasses can override the nested class __qualname__records the nesting and letspickleandreprfind nested classes