A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2000-May/003930.html below:

[Python-Dev] Printing objects on files

[Python-Dev] Printing objects on filesKa-Ping Yee ping@lfw.org
Wed, 3 May 2000 02:41:20 -0700 (PDT)
The following is all stolen from E: see http://www.erights.org/.

As i mentioned in the previous message, there are reasons that
we might want to enable files to know what it means to print
things on them.

    print x

would mean

    sys.stdout.printout(x)

where sys.stdout is defined something like

    def __init__(self):
        self.encs = ["ASCII"]

    def pushenc(self, enc):
        self.encs.append(enc)
    
    def popenc(self):
        self.encs.pop()
        if not self.encs: self.encs = ["ASCII"]

    def printout(self, x):
        if type(x) is type(u""):
            self.write(x.encode(self.encs[-1]))
        else:   
            x.__print__(self)
        self.write("\n")

and each object would have a __print__ method; for lists, e.g.:

    def __print__(self, file):
        file.write("[")
        if len(self):
            file.printout(self[0])
        for item in self[1:]:
            file.write(", ")
            file.printout(item)
        file.write("]")

for floats, e.g.:

    def __print__(self, file):
        if hasattr(file, "floatprec"):
            prec = file.floatprec
        else:
            prec = 17
        file.write("%%.%df" % prec % self)

The passing of control between the file and the objects to
be printed enables us to make Tim happy:

    >>> l = [1/2, 1/3, 1/4]            # I can dream, can't i?

    >>> print l
    [0.3, 0.33333333333333331, 0.25]

    >>> sys.stdout.floatprec = 6
    >>> print l
    [0.5, 0.333333, 0.25]

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.


-- ?!ng




RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4