Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Customizing <code>__setattr__</code> in every class (e.g. as exemplified in my old recipe that @ainab's answer is pointing to, and other answers), only works to stop assignment to INSTANCE attributes and not to CLASS attributes. So, none of the existing answers would actually satisfy your requirement as stated.</p> <p>If what you asked for IS actually exactly what you want, you could resort to some mix of custom metaclasses and descriptors, such as:</p> <pre><code>class const(object): def __init__(self, val): self.val = val def __get__(self, *_): return self.val def __set__(self, *_): raise TypeError("Can't reset const!") class mcl(type): def __init__(cls, *a, **k): mkl = cls.__class__ class spec(mkl): pass for n, v in vars(cls).items(): if isinstance(v, const): setattr(spec, n, v) spec.__name__ = mkl.__name__ cls.__class__ = spec class with_const: __metaclass__ = mcl class foo(with_const): CLASS_CONSTANT = const('this is a constant') print foo().CLASS_CONSTANT print foo.CLASS_CONSTANT foo.CLASS_CONSTANT = 'Oops!' print foo.CLASS_CONSTANT </code></pre> <p>This is pretty advanced stuff, so you might prefer the simpler <code>__setattr__</code> approach suggested in other answers, despite it NOT meeting your requirements as stated (i.e., you might reasonably choose to weaken your requirements in order to gain simplicity;-). But the techniques here might still be interesting: the custom descriptor type <code>const</code> is another way (IMHO far nicer than overriding <code>__setattr__</code> in each and every class that needs some constants AND making all attributes constants rather than picking and choosing...) to block assignment to an instance attribute; the rest of the code is about a custom metaclass creating unique per-class sub-metaclasses of itself, in order to exploit said custom descriptor to the fullest and achieving the exact functionality you specifically asked for.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload