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

CTO debatem1 at gmail.com
Thu May 14 11:32:14 CEST 2009


> 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".

Any which way you slice this it will require that literal code *not*
be interpreted until execution time. There are other ways to do that-
storing it in strings, as George Sakkis does, modifying the language
itself, as is the proposal here, or reading and parsing the original
source. But you're right- more info is needed than what the bytecode
contains.

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

Obviously, you are quite correct. Scoping in particular is difficult
both to understand and to properly handle- had me chasing my tail
for about twenty minutes earlier, actually- and I'm sure this is a
security nightmare, but it does (generally) what is being asked for
here. And it does so without recourse to changing the syntax.

Here's another possible mechanism:

def runtime(f):
	"""Evaluates a function's annotations at runtime."""
	annotations = getfullargspec(f)[-1]
	@wraps(f)
	def wrapped(*args, **kwargs):
		defaults = {k: eval(v) for k, v in annotations.items()}
		defaults.update(kwargs)
		return f(*args, **defaults)
	return wrapped

@runtime
def example1(x, y:'[]'):
	y.append(x)
	return y

@runtime
def example2(x:'a**2+2*b+c'):
	return x

Pretty simple, although it messes with the call syntax pretty
badly, effectively treating a non-keyword argument as a
keyword-only argument. There's probably a way around that
but I doubt I'm going to see it tonight.

The point is, I don't really see the point in adding a new
syntax. There are *lots* of incomplete solutions floating
around to this issue, and it will probably take a lot less
work to make one of those into a complete solution than it
will to add a new syntax, if that makes any sense at all.

Also, do you mind posting any problems you find in that
to the activestate message board so there is a record
there?

Geremy Condra



More information about the Python-ideas mailing list