Bizarre behavior with mutable default arguments

bukzor workitharder at gmail.com
Sun Dec 30 15:11:50 EST 2007


On Dec 30, 2:23 am, thebjorn <BjornSteinarFjeldPetter... at gmail.com>
wrote:
> Scenario: long running server process,
> Bug report: "people aren't getting older", Code:
>
>    def age(dob, today=datetime.date.today()):
>        ...

A very interesting example, thanks.

On Dec 30, 8:25 am, StephenRF... at gmail.com wrote:
> This is a well-known python gotcha.  See:http://www.ferg.org/projects/python_gotchas.html#contents_item_6

Just because it's well known doesn't mean we shouldn't think about it.
For example, in the same list you linked, "3. Integer division" is
being fixed in py3k.


On Dec 30, 8:26 am, George Sakkis <george.sak... at gmail.com> wrote:
> I'm with you on this one; IMHO it's one of the relatively few language
> design missteps of Python, favoring the rare case as the default
> instead of the common one.

Well put. Although I've seen 'potentially useful' often used about
this, I havn't found an instance of its use in production code.

On Dec 30, 9:57 am, thebjorn <BjornSteinarFjeldPetter... at gmail.com>
wrote:
> Our coding standard now dictates:
>
>    def foo(arg=None):
>        if arg is None:
>            arg = <default mutable value>
>
> (unless there's a very good reason to do it otherwise :-)

I believe this is very similar to most people's coding practices. It's
the one I adopted, it's in the above FAQ, the above 'gotchas' list,
and it's all over the standard library. This is a case of a language
feature requiring coding practices to prevent bugs, with very little
value added elsewhere.

--Buck



More information about the Python-list mailing list