Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Decorating an Object with Print-Like Methods

Credit: Jürgen Hermann

Problem

You want functionality similar to that of the print statement on a file object that is not necessarily standard output, and you want to access this functionality in an object-oriented manner.

Solution

Statement print is quite handy, but we can emulate (and optionally tweak) its semantics with nicer, object-oriented syntax by writing a suitable class:

class PrintDecorator:
    """ Add print-like methods to any writable file-like object. """

    def _ _init_ _(self, stream, do_softspace=1):
        """ Store away the stream for later use. """
        self.stream = stream
        self.do_softspace = do_softspace
        self.softspace = 0

    def Print(self, *args, **kw):
        """ Print all arguments as strings, separated by spaces.

            Take an optional "delim" keyword parameter to change the
            delimiting character and an optional "linend" keyword
            parameter to insert a line-termination string. Ignores
            unknown keyword parameters for simplicity.
        """
        delim = kw.get('delim', ' ')
        linend = kw.get('linend', '')
        if self.do_softspace and self.softspace and args: start = delim
        else: start = ''
        self.stream.write(start + delim.join(map(str, args)) + linend)
        self.softspace = not linend

    def PrintLn(self, *args, **kw):
        """ Just like self.Print(  ), but linend defaults to line-feed.
        """
        kw.setdefault('linend','\n')
        self.Print(*args, **kw) if _ _name_ _ == '_ _main_ _': # Here's how you use this: import sys out = PrintDecorator(sys.stdout) out.PrintLn(1, "+", 1, "is", 1+1) out.Print("Words", ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata