Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

302
Vistas
How to make a specific instance of a class immutable?

Having an instance c of a class C, I would like to make c immutable, but other instances of C dont have to.

Is there an easy way to achieve this in python?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can't make Python classes fully immutable. You can however imitate it:

class C:
    _immutable = False
    def __setattr__(self, name, value):
        if self._immutable:
            raise TypeError(f"Can't set attribute, {self!r} is immutable.")
        super().__setattr__(name, value)

Example:

>>> c = C()
>>> c.hello = 123
>>> c.hello
123
>>> c._immutable = True
>>> c.hello = 456
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __setattr__
TypeError: Can't set attribute, <__main__.C object at 0x000002087C679D20> is immutable.

If you wish to set it at initialization, you can add an __init__ like so:

class C:
    _immutable = False
    def __init__(self, immutable=False):
        self._immutable = immutable
    def __setattr__(self, name, value):
        if self._immutable:
            raise TypeError(f"Can't set attribute, {self!r} is immutable.")
        super().__setattr__(name, value)

Keep in mind you can still bypass it by accessing and modifying the __dict__ of the instance directly:

>>> c = C(immutable=True)
>>> c.__dict__["hello"] = 123
>>> c.hello
123

You may attempt to block it like so:

class C:
    _immutable = False
    def __init__(self, immutable=False):
        self._immutable = immutable
    def __getattribute__(self, name):
        if name == "__dict__":
            raise TypeError("Can't access class dict.")
        return super().__getattribute__(name)
    def __setattr__(self, name, value):
        if self._immutable:
            raise TypeError(f"Can't set attribute, {self!r} is immutable.")
        super().__setattr__(name, value)

But even then it's possible to bypass:

>>> c = C(immutable=True)
>>> object.__getattribute__(c, "__dict__")["hello"] = 123
>>> c.hello
123
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda