[Python-Dev] Re: Printing objects on files

Ka-Ping Yee ping@lfw.org
Wed, 3 May 2000 02:51:30 -0700 (PDT)

On Wed, 3 May 2000, Ka-Ping Yee wrote:
> Fantasizing about other useful kinds of state beyond "encs"
> and "floatprec" ("listmax"? "ratprec"?) and managing this
> namespace is left as an exercise to the reader.

Okay, i lied.  Shortly after writing this i realized that it
is probably advisable for all such bits of state to be stored
in stacks, so an interface such as this might do:

    def push(self, key, value):
        if not self.state.has_key(key):
            self.state[key] = []

    def pop(self, key):
        if self.state.has_key(key):
            if len(self.state[key]):

    def get(self, key):
        if not self.state.has_key(key):
            stack = self.state[key][-1]
        if stack:
            return stack[-1]
        return None


    >>> print 1/3

    >>> sys.stdout.push("float.prec", 6)
    >>> print 1/3

    >>> sys.stdout.pop("float.prec")
    >>> print 1/3

And once we allow arbitrary strings as keys to the bits
of state, the period is a natural separator we can use
for managing the namespace.

Take the special case for Unicode out of the file object:
    def printout(self, x):

and have the Unicode string do the work:

    def __printon__(self, file):

This behaves just right if an encoding of None means ASCII.

If mucking with encodings is sufficiently common, you could
imagine conveniences on file objects such as

    def __init__(self, filename, mode, encoding=None):
        if encoding:
            self.push("unicode.enc", encoding)

    def pushenc(self, encoding):
        self.push("unicode.enc", encoding)

    def popenc(self, encoding):

-- ?!ng