Examples of descriptors?

sismex01 at hebmex.com sismex01 at hebmex.com
Mon Jun 2 15:37:13 EDT 2003


> 
> However, I discovered few weeks ago that under 2.3b
> 
> >>> class M(type): pass
> >>> object.__setattr__(M,'x',1)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: can't apply this __setattr__ to type object
> 
> (this broke one program of fine; BTW, I haven't seen this documented
> in http://www.python.org/2.3/highlights.html)
> 
> The problem goes away if I use type.__setattr__:
> 
> >>> type.__setattr__(M,'x',1)
> >>> M.x
> 1
> 
> My question is: what's the rationale for the change ? It is simply
> a performance hack or there was some subtle bug with the previous
> model ?
> 
> Just curious,
>

I believe there was a subtle bug there.  In the previous model,
you could do (such as I did once) something like this (for all
those of you who want a "transitive" list.sort() , which
returns self):

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> def Sort(self, __func=list.sort):
	__func(self)
	return self

>>> L = [9,7,4,2,6,7,8,3]
>>> type(L),L
(<type 'list'>, [9, 7, 4, 2, 6, 7, 8, 3])
>>> L.sort()
>>> type(L),L
(<type 'list'>, [2, 3, 4, 6, 7, 7, 8, 9])
>>> 
>>> ## Now some magic.
>>> 
>>> list.sort = Sort
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in ?
    list.sort = Sort
TypeError: can't set attributes of built-in/extension type 'list'
>>> 
>>> object.__setattr__(list, "sort", Sort)
>>> 
>>> # ta-daa
>>> 
>>> L.sort()
[2, 3, 4, 6, 7, 7, 8, 9]
>>> 

In short, object.__setattr__() allowed you to overwrite attributes
in the basic builtin types.  Here I did something quite harmless,
redefine list.sort() in terms of itself so that it returns the
same instance (buggy though, you can't pass the comparison function
anymore).

But, what if someone overrode some other indispensable function
or method, which wrecked some evi1 havock?  So, Guido took the
responsability of changing the __setattr__ method that get's
called depending if you're calling it for a type or for some
other kind of object.

I don't have an URL to the thread, but it was interesting
enough.

-gca
Advertencia:La informacion contenida en este mensaje es confidencial y
restringida, por lo tanto esta destinada unicamente para el uso de la
persona arriba indicada, se le notifica que esta prohibida la difusion de
este mensaje. Si ha recibido este mensaje por error, o si hay problemas en
la transmision, favor de comunicarse con el remitente. Gracias.





More information about the Python-list mailing list