Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: __dict__ attribute for built-in types

Reply
Thread Tools

Re: __dict__ attribute for built-in types

 
 
Steven D'Aprano
Guest
Posts: n/a
 
      10-28-2011
On Fri, 28 Oct 2011 01:36:41 +0200, candide wrote:

> Le 28/10/2011 00:57, Hrvoje Niksic a écrit :
>
>> was used at class definition time to suppress it. Built-in and
>> extension types can choose whether to implement __dict__.
>>
>>

> Is it possible in the CPython implementation to write something like
> this :
>
> "foo".bar = 42
>
> without raising an attribute error ?


No, because built-in strings don't have a __dict__ and so you cannot add
new attributes that didn't already exist.

But you can subclass str and do whatever you like.

class Str(str):
pass

Str("foo").bar = 42



--
Steven
 
Reply With Quote
 
 
 
 
Steven D'Aprano
Guest
Posts: n/a
 
      10-28-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
 
Reply With Quote
 
 
 
 
Hrvoje Niksic
Guest
Posts: n/a
 
      10-28-2011
candide <(E-Mail Removed)> writes:

> Le 28/10/2011 00:57, Hrvoje Niksic a crit :
>
>> was used at class definition time to suppress it. Built-in and
>> extension types can choose whether to implement __dict__.
>>

>
> Is it possible in the CPython implementation to write something like this :
>
> "foo".bar = 42
>
> without raising an attribute error ?


No, and for good reason. Strings are immutable, so that you needn't
care which particular instance of "foo" you're looking at, they're all
equivalent. The interpreter uses that fact to cache instances of short
strings such as Python identifiers, so that most places that look at a
string like "foo" are in fact dealing with the same instance. If one
could change an attribute of a particular instance of "foo", it would no
longer be allowed for the interpreter to transparently cache them. The
same goes for integers and other immutable built-in objects.

If you really need to attach state to strings, subclass them as Steven
explained. All code that accepts strings (including all built-ins) will
work just fine, transparent caching will not happen, and attributes are
writable.
 
Reply With Quote
 
candide
Guest
Posts: n/a
 
      10-28-2011
Le 28/10/2011 10:01, Steven D'Aprano a écrit :

> didn't think of it. This is hardly a surprise. Wanting to add arbitrary
> attributes to built-ins is not exactly an everyday occurrence.
>




Depends. Experimented programmers don't even think of it. But less
advanced programmers can consider of it. It's is not uncommun to use a
Python class like a C structure, for instance :

class Cass

C.member1=foo
C.member2=bar


Why not with a built-in type instead of a custom class?




> the natural logarithm of a googol (10**100). But it's a safe bet that
> nothing so arbitrary will happen.


betting when programming ? How curious!


> Also, keep in mind the difference between a *class* __dict__ and an
> *instance* __dict__.
>


You mean this distinction

>>> hasattr('', '__dict__')

False
>>> hasattr(''.__class__, '__dict__')

True
>>>



?
 
Reply With Quote
 
candide
Guest
Posts: n/a
 
      10-28-2011
Le 28/10/2011 05:02, Patrick Maupin a crit :

> You can easily do that by subclassing a string:
>
> class AnnotatedStr(str):
> pass
>
> x = AnnotatedStr('Node1')
> x.title = 'Title for node 1'
>



Less or more what I did. But requires to transport the string graph
structure to the AnnotatedStr one.

 
Reply With Quote
 
candide
Guest
Posts: n/a
 
      10-28-2011
Le 28/10/2011 11:08, Hrvoje Niksic a crit :

> longer be allowed for the interpreter to transparently cache them. The
> same goes for integers and other immutable built-in objects.



On the other hand, immutability and optimization don't explain the whole
thing because you can't do something like [].bar = 42.



>
> If you really need to attach state to strings, subclass them as Steven
> explained. All code that accepts strings (including all built-ins) will
> work just fine, transparent caching will not happen, and attributes are
> writable.


OK, thanks, I'll consider it seriously. Actually I have a directed graph
whose nodes are given as string but it's oversimplistic to identify node
and string (for nodes requiring specific methods).
 
Reply With Quote
 
Peter Pearson
Guest
Posts: n/a
 
      10-28-2011
On Fri, 28 Oct 2011 00:52:40 +0200, candide <(E-Mail Removed)> wrote:
[snip]
>>>>> hasattr(42, '__dict__')

>> False

[snip]
>
> Let'have a try :
>
> >>> hasattr(43, '__dict__')

> False
> >>>

>
> so we have proved by induction that no integer instance has a
> dictionnary attribute


You left out an important step in this proof by induction. Observe:

>>> n = 0
>>> hasattr(n, "__dict__")

False
>>> if hasattr(n, "__dict__") is False:

.... hasattr(n+1, "__dict__") is False
....
True

There, now it's proven by induction.

--
To email me, substitute nowhere->spamcop, invalid->net.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
__slots__ vs __dict__ Jean Brouwers Python 5 05-13-2004 04:20 PM
RE: __slots__ vs __dict__ Hornberger, Chris Python 1 05-12-2004 09:35 PM
When is a __dict__ not a __dict__? Derek Fountain Python 1 04-21-2004 10:31 AM
__slots__ replacing __dict__ function anabell@sh163.net Python 1 11-06-2003 09:16 AM
obj.__dict__ expected behavior or bug? Ed Young Python 4 08-10-2003 10:50 AM



Advertisments