[Zope] Problem with hasattr() and Zope 2.8.1

Alec Mitchell apm13 at columbia.edu
Sat Oct 1 00:15:33 EDT 2005


On Friday 30 September 2005 12:49 pm, Doyon, Jean-Francois wrote:
> Hello,
>
> I'm using new-style classes and properties to implement multilingual
> support in my objects. I might therefore have something like:
>
> mything = property(__get_mything)
>
> def __get_mything:
>     return self.__mything_en
>
> (Extremely simplified!)
>
> This works fine.
>
> Now however I'm discovering that doing a hasattr() on anything that starts
> with 2 underscores always returns false!
>
> So hasattr(self, '__thumbnail') doesn't work as expected, but hasattr(self,
> '_thumbnail') DOES! (All other things being equal of course).

This is actually a feature of python.  Names starting with '__' are mangled by 
the interpreter so that they are not directly accessible outside the class 
itself; it is an attempt to simulate private class members.  If you are 
finding yourself in need of using a variable that someone else has decided 
needed to be named with '__' then you may want to rethink what you are doing.  
It is somewhat rare that a python programmer would use this trick, so you 
should probably heed the warning and avoid using it if at all possible.  If 
these are methods that you created then just rename them to use a single or 
preferably no underscores if you need to use them from outside the class 
itself (a single underscore is still bad form, as '_' is an indicator that a 
variable is intended to be private and a suggestion that it only be used in 
the class itself).

Alec Mitchell


More information about the Zope mailing list