gratuitous new features in 2.0

Alex Martelli aleaxit at yahoo.com
Wed Oct 4 10:53:01 EDT 2000


"Toby Dickenson" <mbel44 at dial.pipex.net> wrote in message
news:2d2hts447k9uhk0v0bgdpc40h6sho3ceh9 at 4ax.com...
> "Alex Martelli" <alex at magenta.com> wrote:
>
> >def pprint(*args, endline=1, tofile=sys.stdout):
> >    if hasattr(tofile,'pprint'):
> >        return tofile.pprint(*args,endline)
> >    else:
> >        tofile.write(string.join(map(str, args)))
> >        if endline: tofile.write('\n')
>
> The addition of Unicode strings prompted some discussion about using
> that implementation strategy for the plain 'print' too, to allow
> file-like objects to choose their own character encoding.

Ah -- "wouldn't it be lovely"...!

A similar pattern often emerges, by the way.  A 'classoid' of
objects ('file-like objects', 'sequences', etc) has two (or more)
methods which are _typically_ related in certain ways: if either
is defined, then a canonical way to implement the other follows,
but both might be defined independently for performance or other
tweakish reasons.

Haskell's typeclasses have what strikes me as the right approach
to this.  The typeclass itself lets you define each method's
"canonical form" in terms of the other[s]; a given (concrete)
type 'inherits' the typeclass and must redefine ('override')
any minimal subset of said methods, or more.

To give a silly example in Pythonish hypothetical syntax terms,
imagine a mixin class such as:

class Comparable:
    def more_than(self, other):
        return not self.less_or_equal(other)
    def less_or_equal(self, other):
        return not self.more_than(other)

inheriting Comparable would give you both more_than and
less_or_equal, but you'd have to define (at least) either
one to avoid infinite mutual recursion, of course.  But,
YOU pick which one[s] to override in your class -- whichever
is more natural for your specific case.

print and write methods for output-file-like objects could
be a rather similar case, I think -- define either (or both),
get the canonical correspondence from the mixin class for
the other.  writelines is also in the 'typeclass' of course.


Alex






More information about the Python-list mailing list