Overloading the ">>" operator in Python 2.2.1

Terry Reedy tjreedy at udel.edu
Thu Sep 12 08:57:26 EDT 2002


"Andy Elvey" <andy.elvey at paradise.net.nz> wrote in message
news:fhYf9.1418$b5.128061 at news02.tsnz.net...
> Hi all .
>    I'm using Python 2.2.1 under Win98.  I'm doing some experimenting
with
> parsing, and as part of that, I'm trying to overload the right-shift
> operator (>>) so that I can use it as follows (testing against a
sequence
> that I read in) -
>   a >> b   would mean  "a is followed by b" .
>    So,  you could have a function like seqtest("string_to_test" ,
> "foo">>"bar" ) , and that function would return true or false,
depending on
> whether foo was followed by bar.
>  (  I know it's possible to use regexes for this,  but being able to
create
> a sequence-testing operator like this would be useful .)
>     Many thanks in advance ......

You did not explicitly ask a question, but here's a possible answer
anyway:

>>> class wierd(str):
...   def __rshift__(self,other):
...     print self, 'followed by', other
...
>>> foo = wierd('foo')
>>> bar = wierd('bar')
>>> foo>>bar
foo followed by bar

You cannot add attributes to built-in types.  You can only subclass
them (in 2.2+).

Terry J. Reedy







More information about the Python-list mailing list