Default method arguments

Martin Miller ggrp1.20.martineau at dfgh.net
Tue Nov 15 14:02:38 EST 2005


Alex Martelli wrote, in part:
> If it's crucial to you to have some default argument value evaluated at
> time X, then, by Python's simple rules, you know that you must arrange
> for the 'def' statement itself to execute at time X.  In this case, for
> example, if being able to have self.data as the default argument value
> is the crucial aspect of the program, you must ensure that the 'def'
> runs AFTER self.data has the value you desire.
>
> For example:
>
> class A(object):
>     def __init__(self, n):
>         self.data = n
>         def f(self, x = self.data)
>              print x
>         self.f = f
>
> This way, of course, each instance a of class A will have a SEPARATE
> callable attribute a.f which is the function you desire; this is
> inevitable, since functions store their default argument values as part
> of their per-function data.  Since you want a.f and b.f to have
> different default values for the argument (respectively a.data and
> b.data), therefore a.f and b.f just cannot be the SAME function object
> -- this is another way to look at your issue, in terms of what's stored
> where rather than of what evaluates when, but of course it leads to
> exactly the same conclusion.

FWIT and ignoring the small typo on the inner def statement (the
missing ':'), the example didn't work as I (and possibily others) might
expect.  Namely it doesn't make function f() a bound method of
instances of class A, so calls to it don't receive an automatic 'self''
argument when called on instances of class A.

This is fairly easy to remedy use the standard new module thusly:

import new
class A(object):
    def __init__(self, n):
        self.data = n
        def f(self, x = self.data):
            print x
        self.f = new.instancemethod(f, self, A)

This change underscores the fact that each instance of class A gets a
different independent f() method.  Despite this nit, I believe I
understand the points Alex makes about the subject (and would agree).

-Martin




More information about the Python-list mailing list