[Python-ideas] Default arguments in Python - the return - running out of ideas but...

Arnaud Delobelle arnodel at googlemail.com
Thu May 14 10:08:13 CEST 2009


2009/5/14 CTO <debatem1 at gmail.com>:

> Thanks for the input, but I've already written the code to do this.
> It
> is available at <URL:http://code.activestate.com/recipes/576751/>.

I should have said "it's impossible short of looking at the source
code or doing some very sophisticated introspection of the bytecode of
the module the function is defined in".

Even so, your recipe doesn't quite work in several cases, aside from
when the source code is not accessible.  Two examples:


def nesting():
    default = 3
    @runtime
    def example3(x=default):
        return x
    example3()

nesting()


@runtime
def name(x=a):
    return x

name()

* The first one fails because default is not a global variable, thus
not accessible from within the runtime decorator.  I don't know how if
this can be fixed.  Note that for the function to exec() at all, you
need to e.g. modify remove_decorators so that it also removes initial
whitespace, something like:

def remove_decorators(source):
    """Removes the decorators from the given function"""
    lines = source.splitlines()
    lines = [line for line in lines if not line.startswith('@')]
    indent = 0
    while lines[0][indent] == ' ':
        indent += 1
    new_source = '\n'.join(line[indent:] for line in lines)
    return new_source


* The second one fails because of a clash of names.  I guess that can
be fixed by specifying what the locals and globals are explicitely in
the calls to exec and eval.

-- 
Arnaud



More information about the Python-ideas mailing list