Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Why are you trying to restrict developers from doing that? Is there any technical reason besides "I don't want them to do it" for it? If not, don't do it.</p> <p>Anyway, using <code>__slots__</code> saves memory (no <code>__dict__</code>) so it's the better solution to do it. You won't be able to use it if some of your code needs the object to have a <code>__dict__</code> though.</p> <p>If there is a good reason to restrict it (again, are you sure there is one?) <em>or</em> you need to save that little bit of memory, go for <code>__slots__</code>.</p> <hr> <p>After reading your explanation you might want to use <code>__setattr__</code>, possibly combined with <code>__slots__</code> (you need to store the attribute whitelist somewhere anyway, so you can as well use it to save memory). That way you can display some more helpful information such as which <em>similar</em> attribute are available. A possible implementation could look like this:</p> <pre><code>class Test(object): __slots__ = ('foo', 'bar', 'moo', 'meow', 'foobar') def __setattr__(self, name, value): try: object.__setattr__(self, name, value) except AttributeError: alts = sorted(self.__slots__, key=lambda x: levenshtein(name, x)) msg = "object has no attribute '{}', did you mean '{}'?" raise AttributeError(msg.format(name, alts[0])) </code></pre> <p>The <code>levenshtein()</code> I tested it with was implementation #4 from <a href="http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python" rel="nofollow">this site</a>. In case of <em>not so smart</em> users you might want to make the error even more verbose and include all close matches instead of just the first one.</p> <p>You can further improve the code by creating a mixin class containing just the <code>__setattr__</code> method. That way you can keep the code out of your real classes and also have a custom <code>__setattr__</code> if necessary (just use <code>super(...).__setattr__(...)</code> in the mixin instead of <code>object.__setattr__</code>)</p>
 

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