] In general, follow Guido's style conventions, ] but I have some quirks that I prefer (although I could be talked ] out of them): ... ] * _ instead of self as first argument to methods: def f(_, x): ...
I dunno; I think sample code should (a) stick rather conservatively to typical usage, apart from the concept being illustrated of course; and (b) strive for maximum readability. For Python, both principles demand that one should write: def foo(bar): if is_list(bar): return sum(map(foo, bar)) else: return [bar] instead of: def foo(bar): if is_list(bar): return sum(map(foo, bar)) else: return [bar] This may be one of those things that only makes sense if you've not a Lisp programmer. (wink) To stray from the topic: I find I only disagree with three points in Peter Norvig's enlightening table of Lisp vs. Python features. <http://www.norvig.com/python-lisp.html> 1. That "x.slot = y" is not user-extensible. The __setattr__() method does this. 2. That Python's relative lack of control structures is necessarily worse than Lisp's abundance of them. Especially for students, I think this: if is_list(n): return foo_l(n) elif is_str(n) or is_int(n): return foo_a(n) else: raise TypeError is at least as clear, though not as brief, as this: (etypecase n (list (foo-l n)) ((or string integer) (foo-a n))) with the obligatory note in the text to the effect that "'Etypecase' is a form similar to 'case' which selects a clause based on the type..." and so on. 3. That Python doesn't support generic programming. Generic algorithms are expressed as naturally in Python as in any language I know: from operator import add def sum(items): return reduce(add, items) >>> sum([3, 4, 5]) 12 >>> sum([3, 4j, 4-2j]) (7+2j) >>> sum(["py", "th", "o", "n"]) 'python' Likewise it's natural to write functions that can operate on "any sequence", not just lists or tuples, "any file-like object", not just a real file, "any function-like object", etc. Perhaps something more specific is meant by "generic programming". Cheers, ## Jason Orendorff http://www.jorendorff.com/