Welcome, guest | Sign In | My Account | Store | Cart

The following code shows how to "decorate" objects with new functions, in this case any stream with two methods that work similar to the built-in "print" statement.

Python, 26 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class PrintDecorator:
    """Add print-like methods to any file-like object."""

    def __init__(self, stream):
        """Store away the stream for later use."""
        self.stream = stream

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

            Take an optional "delim" keyword parameter, to change the
            delimiting character.
        """
        delim = kw.get('delim', ' ')
        self.stream.write(delim.join(map(str, args)))

    def PrintLn(self, *args, **kw):
        """ Just like print(), but additionally print a linefeed.
        """
        self.Print(*args+('\n',), **kw)

import sys
out = PrintDecorator(sys.stdout)
out.PrintLn(1, "+", 1, "is", 1+1)
out.Print("Words", "Smashed", "Together", delim='')
out.PrintLn()

Print() takes any number of positional arguments, converts them to strings (via the map() and str() built-ins) and finally joins them together using the given "delim", then writes the result to the stream.

PrintLn() adds the newline character to the set of arguments and then delegates to Print(). We could also first call Print() and then output an additional LF character, but that may pose problems in multi-tasking environments, e.g. when doing concurrent writes to a log file.

The code uses Python 2.0 syntax (string methods, new-style argument passing), it can be easily ported to Python 1.5.2 by using apply() and the string module.