[Python-ideas] Access to function objects

Nick Coghlan ncoghlan at gmail.com
Tue Aug 9 05:25:16 CEST 2011

On Tue, Aug 9, 2011 at 11:36 AM, Ben Finney <ben+python at benfinney.id.au> wrote:
> Which code object, though? If we can't get at the innermost function
> (which is the code location we're interested in) handling the URL, how
> will we get its line number?

In general, you can't, since Python can't readily tell the difference
between decorators that wrap a function and those that replace it
completely. Even the '__wrapped__' convention adopted by recent
incarnations of functools.wraps (primarily to expose the function
underlying lru_cache) only works for genuine wrapper functions that
use that decorator.

>From outside, a cell referencing the current function (if it was
implemented that way) wouldn't tell you anything new, since the
following identity would hold:

    f is f.__closure__[f.__code__.co_freevars.index('__func__')].cell_contents

On any given function, *if* the new cell existed at all, it would
refer to that specific function, not an inner one.


P.S. An example with the existing PEP 3135 implicit cell creation:

>>> class C:
...     def f(self):
...       print(__class__)
>>> f = C.f
>>> C is f.__closure__[f.__code__.co_freevars.index('__class__')].cell_contents

Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list