Invisible function attributes

Peter Otten __peter__ at web.de
Wed Sep 3 11:38:50 EDT 2003


def foo():
    try:
        foo.a += 1 # executed every time you call the function
    except AttributeError:
        foo.a = 1 # set to one if it's not already there

foo.b = 1 # executed once

print vars(foo) # function body not yet called {'b': 1}

for i in range(3):
    foo()
    print vars(foo)

Loop output is

{'a': 1, 'b': 1}
{'a': 2, 'b': 1}
{'a': 3, 'b': 1}

That is all perfectly sane as code in the function body is never executed
unless you call the function, whereas code on the module level is executed
immediately as the module is imported. So put foo.attr = ... into the
function body iff you want it to execute every time the function is
invoked; otherwise put it into the module startup code, i. e. do not indent
it.

Peter





More information about the Python-list mailing list