Why ask Why ? ( Was: Why don't stringobjects have methods? )

Steven D. Majewski (sdm7g@elvis.med.Virginia.EDU)
Fri, 1 Apr 1994 18:38:52 GMT

On Apr 1, 9:54, Jim Roskind wrote:

> My approach to dealing with this slight misfeature (python's desire to
> print what remains on a line) is:
> a) When forced to, assign the return value to a garbage
> temporary variable.
> b) When I define a class, I add an "ignore()" method which
> returns None :-)
> Approach a is pretty sub-optimal, as it waste an entry in the dictionary,
> takes the time to do unnecessary assignment, etc.
> For example of approach b, in my profiler, I can write lines such as:
> Stats('profile.1').sort_stats(1).print_stats().ignore()
> I can believe that some folks will see the above as an aberration of
> nature, but I find it very readable. :-) :-)

An alternative, which *I* think is more obvious of intent is:

>>> Stats('profile.1').sort_stats(1).print_stats() and None

( See: The Collected Obfuscated Python of S.D.Majewski, vol V. )

Just make certain not to swap them!

>>> None and Stats('profile.1').sort_stats(1).print_stats()

is ALSO a non printing statement with different effects.

I thought perhaps we could use the difference between an
objects __repr__ and its __str__ methods to pull a fast one,

>>> from obj import *
>>> class Thing( Object ):
... def __repr__( self ): return None
... def __str__( self ): return repr( self._obj )
>>> a = Thing( 1 )
>>> a

Traceback (innermost last):
File "<stdin>", line 1
TypeError: repr not string

The return value has to be a *string*, and:

>>> class Othing( Object ):
... def __repr__( self ) : return ''
... def __str__( self ): return repr( self._obj )
>>> o = Othing( 1 )
>>> o

>>> print o

A NULL string still prints the empty string and a newline.

[ Class Object() is an Ultra, Ultra Secret project that,
other than myself, only Tommy knows about!
But I suspect that Tim can guess...
We'll just have to have him shot! ;-) ]

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics