Function name unchanged in error message

Steven D'Aprano steve at
Sun Jan 31 04:43:56 CET 2010

On Sat, 30 Jan 2010 14:26:43 -0800, andrew cooke wrote:

> On Jan 29, 11:50 am, exar... at wrote:
>> new.function and new.code will let you construct new objects with
>> different values (and copying over whichever existing attributes you
>> want to preserve).
> unfortunately new is deprecated and dropped from 3.  i can't see how the
> same functionality is available in the types module for 3 - am i missing
> something obvious?

You have to get the constructor from an existing object. type(obj) will 
always return the type object, which you can use as a constructor.

>>> newfunction = type(lambda: None)
>>> newcode = type((lambda: None).__code__)

Possibly even easier:

>>> import types
>>> types.FunctionType is newfunction
>>> types.CodeType is newcode

So that's two ways to get a constructor. Now all we need is to learn how 
they work:

>>> help(newfunction)

Help on class function in module builtins:

class function(object)
 |  function(code, globals[, name[, argdefs[, closure]]])
 |  Create a function object from a code object and a dictionary.

>>> help(newcode)

Help on class code in module builtins:

class code(object)
 |  code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,
 |        constants, names, varnames, filename, name, firstlineno,
 |        lnotab[, freevars[, cellvars]])
 |  Create a code object.  Not for the faint of heart.

Not for the faint of heart indeed! The best way of using this is to copy 
the parameters from an existing code object, one created by using def. 
Look for attributes of f.__code__ starting with "co_".

Don't forget compile as well, which may help.


More information about the Python-list mailing list