Perl/Python/Ruby common backend (Parrot, can Ruby play too?)

Alex Martelli aleaxit at yahoo.com
Tue Aug 7 11:30:33 EDT 2001


"Tom Robinson" <tom at alkali.spamfree.org> wrote in message
news:8afvmt8ck86d7ug5clnu3h0qek4hb7ope0 at 4ax.com...
    ...
> >> need that might be unique to Ruby?  [One that comes to mind: the
ability
> >> to extend an existing class.]  For the
> >
> >In what sense is this "unique to Ruby"?  The following works in Python:
    ...
> He might be talking about the way you can reopen and extend existing
> _built_in_ classes in Ruby, for example:

Ah, I see -- Python's classes aren't divided between builtin and
not-builtin (they all work the same way), but there's a distinction
between classes and *types* (which is slowly and gradually being
removed) -- types cannot be manipulated as freely as classes.

> class Regexp
>   alias oldcomp =~
>   def =~ (astring)
>      match(astring)[1..9]
>   end
> end
>
> ...Regexp being part of the standard library.  Can you do this in
> Python?  It would be nice...

Python's re module offers factories for re-object that are
instance of types, not of classes -- therefore, in Python's
current version, no such manipulation is possible.  The
current Pythonic solution is to wrap type instances into
class instances (see my recipe
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295
to see how auto-delegation replaces inheritance for this
kind of purposes), whereupon all manipulation becomes
possible (and easy).  Of course, the module itself would
be replaced with one that wraps it and supplies factory
functions returning the wrapped-objects directly (using
techniques close to the one I show in my popular recipe
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207).

But this doesn't retroactively affect type-instances that
were created *before* the wrapping, so it's not fully
equivalent to what one can do starting in Python 2.2
(which introduces type->class inheritance and a few other
such enhancements -- definitely a start on the road of
type/class equivalence).  In particular, such polymorphic
'tricks', just like about any kind of polymorphism, are
defeated by the accursed practice of type-testing (I
recommend some alternatives in my recipe
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52291).


Alex






More information about the Python-list mailing list