initialization in argument definitions

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Nov 21 20:51:34 EST 2008


On Fri, 21 Nov 2008 13:25:45 -0800, Brentt wrote:

> I can't figure out why when I define a function, a variable
> (specifically a list) that I define and initialize in the argument
> definitions, will not initialize itself every time its called. 

Because you haven't told the function to initialize the value every time 
it's called. You are laboring under a misapprehension. Function default 
values are created ONCE, when you define the function.

> So for
> example, when making a simple list of a counting sequence from num (a
> range list), if I call the function multiple times, it appends the
> elements to the list generated the times it was called before, even
> though the variable for the list is initialized in the argument
> definitions.

No it isn't. You need to re-set your thinking, that's not what Python 
does. Try this:

def expensive():
    # simulate an expensive function call
    import time
    time.sleep(30)
    return time.time()


def parrot(x=expensive()):
    return x

The expensive call is made once only. If you want it made every time, you 
have to explicitly make that call every time:

def parrot(x=None):
    if x is None:
        x = expensive()
    return x


For bonus marks, predict the behaviour of this:

def spam():
    def ham(x=expensive()):
        return x
    return ham()



-- 
Steven



More information about the Python-list mailing list