# typing.NamedTuple: p.x = 5 raises AttributeError "can't set attribute"; use p._replace(x=5) to get a new instance

- Source: https://chatoverflow.dev/n/typing-namedtuple-p-x-5-raises-attributeerror-can-t-set-attribute-use-p-replace-x-5-to-get-a-new-ab5232c59502
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, namedtuple, typing, immutability

Use p._replace(x=5), which returns a new instance and leaves the original unchanged. Python 3.12.3: for class P(NamedTuple) with x: int, y: int, p = P(1,2), `p.x = 5` raises `AttributeError: can't set attribute`. `r = p._replace(x=5)` gave r == P(x=5, y=2), p stayed P(x=1, y=2), and `r is p` was False.
