List - rotate

Alex Martelli aleax at aleax.it
Fri Jan 25 10:32:08 EST 2002


"ameoba" <ahmebah at hotmail.com> wrote in message
news:Xns91A13F4A6BAA3ahmebahhotmailcom at 198.99.146.10...
> "Alex Martelli" <aleax at aleax.it> wrote in
news:a2mf02$86k$1 at serv1.iunet.it:
>
> > s[1:]+s[0:1] yields a "rotated copy" for ANY sequence s, be it
> > a string, a list, a tuple, whatever.  But you need to
> > assign it to something, else it will go away as soon
> > as you're done with it.  It does NOT modify s in-place
> > in any case (strings and tuples are mutable, lists are
> > mutable but no mutation is performed in this case).
>
> Of course, this is easily abstractable to rotating a list by any arbitrary
> ammount...

well, yes, x[n:]+x[:n] isn't hard (actually nicer than the above,
as the leading 0 in the second slice is redundant there:-).

> But it got me to wondering;  is there a good way to add a
> method to strings?
>
> Not so much to make a class derived from the string type, but just to add
a
> function to it.

No, built-in string objects do not carry around a __dict__ for the
purpose, and nor does the str object itself, so no attributes can
be added to either.


> If it can't be done with a built-in class like string, can methods be
added
> to user-defined classes outside of the original class definition without
> subclassing them?

It depends on the metaclass (the class's class), just as the ability
to add attributes to an instance depend on the instance's class.  The
only two metaclasses commonly used these days, types.ClassType (for
'classic clases') and the builtin type (for classes deriving directly
or indirectly from object) both allow this kind of modification.


> Not so much that I want to do this, just that I'm curious as to how
dynamic
> of an environment Python really is.

It's rather dynamic, but there was substantial debate last year about
how dynamic it's gonna stay; I had the impression that Guido would like
it a bit less dynamic than it currently is (to ease future optimization,
avoid too-pitch-dark lack magic, etc).  Still, with respect to the way
it seemed destined to be from the earliest attempts at 2.2, its' gone a
lot of the way back towards the high dynamism of 2.1, _at least in the
current implementation_.  For example, it's now possible again to
rebind the __dict__ of an object, which was forbidden for "new style"
instance objects in the earliest days of 2.2.

Still, the PEPs about 2.2-and-later enhancements leave the issue open,
claiming undefined status for certain kinds of modifications (I'm not
even quite sure WHICH kinds of modifications).  They used to work (in
2.1, with a very simple object-model behind the surface, just lacquered
over a bit); they mostly work again now in 2.2 (despite a richer and
deeper object-model); but I wouldn't exactly want to bet my shirt on
what's going to happen in 2.3 and beyond, on this score.


Alex






More information about the Python-list mailing list