Any way of adding methods/accessors to built-in classes?

Paddy paddy3118 at netscape.net
Wed Oct 25 16:08:33 EDT 2006


Kenneth McDonald wrote:
> This is possible with pure Python classes. Just add the method as new
> attribute of the class. However, that won't work for the builtins.
>
> I know that this is somewhat dangerous, and also that I could subclass
> the builtins, but not being able to do things like '[1,2,3]'.length
> drives me a little nuts. Python is about the only computer language I
> use, and I think it's certainly the best of the scripting languages, but
> there are inconsistencies in the object model and some other things I
> wish I could fix. If could could modify the builtins this way, I'd be
> willing to take the risk.
>
> Thanks,
> Ken

Hi Ken,
The reason comes from code being read much more than it is written. It
makes it much easier to maintain code if some foundations i.e. the
builtins, don't change.  That way everyone maintaining the code will
know that an int is an int, is an int, wherever it may be in the source
files of your program. The flip-side is that someone reading List in
athers code knows it isn't the built-in list type and so is on-guard
for any deviations/additions.

As for your irritation Ken, if you have to maintain code, as I do/have
done, then you remember how many times little inconsistencies have
tripped you up in the past, and offset those gripes against things like
this. 

- cheers, Paddy.




More information about the Python-list mailing list