[Python-checkins] r43728 - sandbox/trunk/overload/prettyprinting.py
guido.van.rossum
python-checkins at python.org
Sat Apr 8 06:13:47 CEST 2006
Author: guido.van.rossum
Date: Sat Apr 8 06:13:47 2006
New Revision: 43728
Added:
sandbox/trunk/overload/prettyprinting.py (contents, props changed)
Log:
A really stupid prettyprinter, showing how to inherit an overloaded function.
(The solution isn't as natural as I'd like it to be, but not 100% bad.)
Added: sandbox/trunk/overload/prettyprinting.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/overload/prettyprinting.py Sat Apr 8 06:13:47 2006
@@ -0,0 +1,59 @@
+#!/usr/bin/env python2.5
+
+"""Pretty-printing Python data structures.
+
+This is a sample testcase for function overloading.
+
+"""
+
+import sys
+
+from overloading import overloaded
+
+__metaclass__ = type
+
+class PrettyPrinter:
+
+ def __init__(self, stream=None, width=80):
+ self.stream = stream if stream is not None else sys.stdout
+ self.width = width
+ self.indent = 0
+
+ def write(self, text):
+ for line in text.splitlines(True):
+ self.stream.write(line)
+ if self.indent and line.endswith("\n"):
+ self.stream.write(" "*self.indent)
+
+ @overloaded
+ def pprint(self, obj):
+ self.write(repr(obj))
+
+ @pprint.register(object, list)
+ def pprint_list(self, obj):
+ if not obj:
+ self.write("[]")
+ return
+ sep = "["
+ self.indent += 1
+ for item in obj:
+ self.write(sep)
+ self.pprint(item)
+ sep = ",\n"
+ self.indent -= 1
+ self.write("]")
+
+class HexPrettyPrinter(PrettyPrinter):
+
+ @overloaded
+ def pprint(self, obj):
+ PrettyPrinter.pprint(self, obj)
+
+ @pprint.register(object, int)
+ @pprint.register(object, long)
+ def pprint_hex(self, obj):
+ self.write(hex(obj))
+
+PrettyPrinter().pprint([1, 2, [3, 4], 5, 6])
+print
+HexPrettyPrinter().pprint([1, 2, [3, 4], 5, 6])
More information about the Python-checkins
mailing list