pre-PEP: The create statement

Ben Cartwright bencvt at gmail.com
Thu Apr 6 22:17:14 EDT 2006


Michael Ekstrand wrote:
> Is there a natural way
> to extend this to other things, so that function creation can be
> modified? For example:
>
> create tracer fib(x):
>     # Return appropriate data here
>     pass
>
> tracer could create a function that logs its entry and exit; behavior
> could be modifiable at run time so that tracer can go away into oblivion.
>
> Given the current semantics of create, this wouldn't work. What would be
>  reasonable syntax and semantics to make something like this possible?

The standard idiom is to use a function wrapper, e.g.

def tracer(f):
    def wrapper(*args):
        print 'call', f, args
        result = f(*args)
        print f, args, '=', result
        return result
    return wrapper

def fact(x):
    if not x: return 1
    return x * fact(x-1)
fact = tracer(fact)  # wrap it

The decorator syntax was added in Python 2.4 to make the wrapper
application clearer:

@tracer
def fact(x):
    if not x: return 1
    return x * fact(x-1)

http://www.python.org/dev/peps/pep-0318

--Ben




More information about the Python-list mailing list