Skip to content

Consider allowing frozendicts to be assigned to instance dicts #145119

Closed as not planned

Description

@rhettinger

Currently, can make an assignment to an instance's __dict__ attribute but the value must be an actual dict. It should allow frozendict as well.

This would be useful for making immutable instances without the awkward work arounds used in frozen dataclasses.

>>> class Point:
...     def __init__(self, x, y):
...         self.__dict__ = frozendict(x=x, y=y)
...
        
>>> p = Point(10, 20)
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    p = Point(10, 20)
  File "<pyshell#52>", line 3, in __init__
    self.__dict__ = frozendict(x=x, y=y)
TypeError: __dict__ must be set to a dictionary, not a 'frozendict'

Linked PRs

Activity

  1. added 2 commits that reference this issue on Feb 22, 2026
  2. mpkocher commented on Mar 4, 2026

    @mpkocher
    Contributor

    Some other considerations:

    • frozendict "immutable" style is adding entropy
    • creates challenges for linting tools and static analysis tools to understand the "immutable" semantics

    Also, to be pedantic, I'm not sure that frozendict fundamentally mean it's immutable.

    class Point:
        def __init__(self, x, y):
            self.__dict__ = frozendict(x=x, y=y)
            
        def move_x(self, x):
            self.__dict__ |= frozendict(x=x)

    Adding self.__dict__:Final = frozendict(x=x, y=y) might help, but I don't think this is a good pattern to encourage.

    I think the current dataclasses model is a reasonable way to have immutability in Python.

  3. sergey-miryanov commented on Mar 4, 2026

    @sergey-miryanov
    Contributor

    self.__dict__ |= frozendict(x=x) - you create a new frozendict.

  4. mpkocher commented on Mar 4, 2026

    @mpkocher
    Contributor

    self.__dict__ |= frozendict(x=x) - you create a new frozendict.

    Correct. That's the point I'm trying to make.

    Is the self.__dict__ usage any different than x in the example below?

    @dataclass
    class A:
        x: frozenset[int]
        
        
    a = A(frozenset({1,2}))
    a.x |= frozenset({3,4})
  5. vstinner commented on Mar 5, 2026

    @vstinner
    Member

    Also, to be pedantic, I'm not sure that frozendict fundamentally mean it's immutable.

    If we want to make it more immutable, one option would be to disallow setting/deleting object.__dict__ if it's a frozendict.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions