Note that there are some explanatory texts on larger screens.

plurals
  1. POClass-level read-only properties in Python
    primarykey
    data
    text
    <p>Is there some way to make a class-level read-only property in <a href="http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29" rel="nofollow noreferrer">Python</a>? For instance, if I have a class <code>Foo</code>, I want to say:</p> <pre><code>x = Foo.CLASS_PROPERTY </code></pre> <p>but prevent anyone from saying:</p> <pre><code>Foo.CLASS_PROPERTY = y </code></pre> <p><strong>EDIT:</strong> I like the simplicity of <a href="https://stackoverflow.com/questions/1735434/class-level-read-only-properties-in-python/1735726#1735726">Alex Martelli's solution</a>, but not the syntax that it requires. Both his and <a href="https://stackoverflow.com/questions/1735434/class-level-read-only-properties-in-python/1735615#1735615">~unutbu's answer</a>s inspired the following solution, which is <em>closer</em> to the spirit of what I was looking for:</p> <pre><code>class const_value (object): def __init__(self, value): self.__value = value def make_property(self): return property(lambda cls: self.__value) class ROType(type): def __new__(mcl,classname,bases,classdict): class UniqeROType (mcl): pass for attr, value in classdict.items(): if isinstance(value, const_value): setattr(UniqeROType, attr, value.make_property()) classdict[attr] = value.make_property() return type.__new__(UniqeROType,classname,bases,classdict) class Foo(object): __metaclass__=ROType BAR = const_value(1) BAZ = 2 class Bit(object): __metaclass__=ROType BOO = const_value(3) BAN = 4 </code></pre> <p>Now, I get:</p> <pre><code>Foo.BAR # 1 Foo.BAZ # 2 Foo.BAR=2 # Traceback (most recent call last): # File "&lt;stdin&gt;", line 1, in &lt;module&gt; # AttributeError: can't set attribute Foo.BAZ=3 # </code></pre> <p>I prefer this solution because:</p> <ul> <li>The members get declared inline instead of after the fact, as with <code>type(X).foo = ...</code></li> <li>The members' values are set in the actual class's code as opposed to in the metaclass's code.</li> </ul> <p>It's still not ideal because:</p> <ul> <li>I have to set the <code>__metaclass__</code> in order for <code>const_value</code> objects to be interpreted correctly.</li> <li>The <code>const_value</code>s don't "behave" like the plain values. For example, I couldn't use it as a default value for a parameter to a method in the class.</li> </ul>
    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.
 

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