andrew cooke wrote: > Is there any way to change the name of the function in an error > message? In the example below I'd like the error to refer to bar(), > for example (the motivation is related function decorators - I'd like > the wrapper function to give the same name) > >>>> def foo(): > ... return 7 > ... >>>> foo.__name__ = 'bar' >>>> foo(123) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: foo() takes no arguments (1 given)
The name is looked up in the code object. As that is immutable you have to make a new one: argnames = 'argcount nlocals stacksize flags code consts names varnames filename name firstlineno lnotab'.split() def f(): return 42 code = type(f.func_code) function = type(f) def make_code(proto, **kw): for name in argnames: if name not in kw: kw[name] = getattr(proto, "co_" + name) values = [kw[name] for name in argnames] return code(*values) if __name__ == "__main__": def foo(): print "foo" c = make_code(foo.func_code, name="bar") foo.func_code = c foo(42) Peter -- http://mail.python.org/mailman/listinfo/python-list