[Python-3000] State of the object system

Kay Schluehr kay.schluehr at gmx.net
Thu May 18 08:48:01 CEST 2006


Michael Chermside schrieb:

>Unfortunately, for implementation reasons you can't modify most
>built-in (and some user-defined) classes in this fashion:
>
>   >>> int.func2 = func2
>
>   Traceback (most recent call last):
>     File "<pyshell#35>", line 1, in -toplevel-
>       int.func2 = func2
>   TypeError: can't set attributes of built-in/extension type 'int'
>
>Most Python programmers would probably agree that this is a
>perfectly fine restriction. Built-in classes like int and dict
>are widely used... allowing the code from any one module to
>modify them has dangerously non-local effects. 
>
And that's not true for user defined classes?

The disadvantage of subclassing e.g. int is losing algebraic properties 
that are implicitely defined by the operators. Adding two ints a and b 
results in a third int c, so we have the automorphism:  int + int -> 
int. On subclasses the operation doesn't preserve structure. Adding a 
method isprime() or iseven() to a subclass of int will suddenly be lost 
in the resulting object after an operation as long as it is not 
overwritten to return the right type and not the base type. So it is 
questionable if subclassing is really a good design decision.

>(Yes, I know...
>it works OK for Ruby... but I, for one, am still wary.) If
>your code really needs to modify the behavior of int (or dict
>or whatever) then use a subclass of int (or dict or whatever)
>in your own code which you can modify freely.
>  
>
AFAIK Ruby doesn't support standalone functions but needs a class 
context to define them as methods. Python might be more liberal in this 
respect but it seems to me that it forces to write functions in certain 
situations. A function isprime() has really no place in a subclass of 
int. But it has also no other natural namespace than int. So people 
start writing modules that grant asylum for homeless functions. 
Uncountably many "util" modules tell us bitter stories about non-design 
design ( I'm not innocent of course ).

>But if you've got a convincing argument (preferably with use
>cases that are only poorly addressed by today's Python) for why
>this behavior ought to be added to Py3K... please let us know!
>  
>
Sometimes a broken structure needs more justification than a sound one. 
Arbitrary restrictions complicate the language semantics for no good 
reasons. But if it is strongly encouraged not to add methods to classes 
at runtime we might get rid of the self parameter that lessens the 
barrier between functions and methods?

Regards,
Kay




More information about the Python-3000 mailing list