Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've thought of what I think is a cleaner solution for implementing a pure read-only attribute, if that's all you want. It's a variant of the solution tangentstorm gave, but dispenses with the need for a <code>__getattr__</code> method altogether.</p> <pre><code>class Foo(object): def __init__(self): self.readonly = set() def set_readonly(self, attr, value): setattr(self, attr, value) self.readonly.add(attr) def __setattr__(self, attr, value): if hasattr(self, "readonly") and attr in self.readonly: raise AttributeError("Read only attribute: %s" % (attr,)) object.__setattr__(self, attr, value) </code></pre> <p>It works like this:</p> <pre><code>&gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f.x = 5 &gt;&gt;&gt; f.set_readonly("y", 9) &gt;&gt;&gt; f.x, f.y (5, 9) &gt;&gt;&gt; f.x = 7 &gt;&gt;&gt; f.y = 1 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "ro.py", line 13, in __setattr__ raise AttributeError("Read only attribute: %s" % (name,)) AttributeError: Read only attribute: y </code></pre> <p>Making a read-only attribute read-write again is easy:</p> <pre><code> def unset_readonly(self, attr): self.readonly.remove(attr) </code></pre> <p>In my first attempt at writing this idea I used <code>self.__readonly</code> instead of <code>self.readonly</code>, but that leads to a problem with actually setting the <code>__readonly</code> attribute, since I'd need to do un-munge the "private" attribute to check for its presence (<code>hasattr(self, "_Foo__readonly")</code>), and this is discouraged.</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.
 

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