[Python-ideas] Documenting Python warts

Chris Angelico rosuav at gmail.com
Wed Jan 2 01:34:47 CET 2013


On Wed, Jan 2, 2013 at 11:01 AM, Oleg Broytman <phd at phdru.name> wrote:
>    What about warts that don't have internal sense? Mutable default
> parameters are just artifacts of the implementation. What is their
> "internal sense"?

They let you use a function for something where you'd otherwise need
to instantiate an object and play with it. Take caching, for instance:

def name_lookup(name,cache={}):
  if name not in cache:
    cache[name] = some_lengthy_operation
    # prune the cache of old stuff to keep its size down
  return cache[name]

You can ignore the default argument and pretend it's all magic, or you
can explicitly run a separate cache:

name_lookup("foo",{})   # easy way to say "bypass the cache"

# Do a bunch of lookups that won't be in the main cache, and which
would only pollute the main cache for later
local_name_cache = {}
[name_lookup(n,local_name_cache) for n in names]

The other consideration here is of side effects. It's all very well to
wave a magic wand and say that:

def foo(x,y=[]): pass

will create a unique list for each y, but what about:

def foo(x,y=open("main.log","w")): pass

or similar? Should it reopen the log every time? Should it reevaluate
the expression? There's an easy way to spell it if you want that
behaviour:

def foo(x,y=None):
  if y is None: y=whatever_expression_you_want

(or using object() if None is a legal arg).

Whichever way mutable objects in default args are handled, there are
going to be strangenesses. Therefore the best thing to do is (almost
certainly) the simplest.

>    Paraphrasing Alan Cooper from "The Inmates are Running the Asylum":
> The phrase "experienced Python programmer" really means the person has
> been hurt so many times that the scar tissue is thick enough so he no
> longer feels the pain.

That applies to PHP, and possibly to C (though if you treat C as "all
the power of assembly language, coupled with all the readability of
assembly language", then it doesn't hurt nearly as much as if you try
to treat it as a modern high level language). I'm not so sure it
applies to Python.

ChrisA



More information about the Python-ideas mailing list