__dict__ attribute for built-in types
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Oct 28 04:01:15 EDT 2011
On Fri, 28 Oct 2011 00:52:40 +0200, candide wrote:
> Le 28/10/2011 00:19, Steven D'Aprano a écrit :
>>
>> What, you think it goes against the laws of physics that nobody thought
>> to mention it in the docs?<wink>
>
>
> No but I'm expecting from Python documentation to mention the laws of
> Python ...
You seem to have missed my point. You said "I can't imagine" that the
Python docs fail to mention that built-ins don't allow the addition of
new attributes. I can, easily. The people writing the documentation are
only human, and if they failed to mention it, oh well, perhaps they
didn't think of it. This is hardly a surprise. Wanting to add arbitrary
attributes to built-ins is not exactly an everyday occurrence.
>>> But beside this, how to recognise classes whose object doesn't have a
>>> __dict__ attribute ?
>>
>> The same way as you would test for any other attribute.
>>
>>>>> hasattr(42, '__dict__')
>> False
>
> OK but I'm talking about classes, not instances : 42 has no __dict__
> attribute but, may be, 43 _has_ such attribute, who knows in advance ?
> ;)
True, it is theoretically possible that (say) only odd numbers get a
__dict__, or primes, or the smallest multiple of seventeen larger than
the natural logarithm of a googol (10**100). But it's a safe bet that
nothing so arbitrary will happen.
Dunder attributes ("Double UNDERscore") like __dict__ are reserved for
use by Python, and __dict__ has known semantics. You can safely assume
that either *all* instances of a type will have a __dict__, or *no*
instances will have one. If some class violates that, oh well, your code
can't be expected to support every badly-designed stupid class in the
world.
Also, keep in mind the difference between a *class* __dict__ and an
*instance* __dict__.
>>> hasattr(int, '__dict__') # Does the int class/type have a __dict__?
True
>>> hasattr(42, '__dict__') # Does the int instance have a __dict__?
False
--
Steven
More information about the Python-list
mailing list