[Python-Dev] co_firstlineno on decorated functions

Terry Reedy tjreedy at udel.edu
Tue Aug 3 19:25:28 CEST 2010


On 8/3/2010 8:48 AM, Antoine Pitrou wrote:
> On Tue, 3 Aug 2010 22:25:01 +1000
> Nick Coghlan<ncoghlan at gmail.com>  wrote:
>> On Tue, Aug 3, 2010 at 1:40 PM, Eli Bendersky<eliben at gmail.com>  wrote:
>>> The first print out correctly specifies the line "def foo" is in. However,
>>> the second one points to the line with "@dummydecorator" instead of "def
>>> bar". [Python 2.6]
>>>
>>> The side-effects of this behavior can be easily seen in the output of
>>> modules like trace and profile. Would you say it's normal, or could this be
>>> considered a bug?
>>
>> Since the decorator is as much a part of the function definition as
>> the def line is, I would say that it is correct (the name says
>> "firstlineno", not "deflineno").
>
> That's debatable. Since writing:
>
> @b
> def a():
>      ...
>
> is equivalent to:
>
> def a():
>      ...
> a = b(a)

The difference is that 'a=b(a)' is a standalone statement which could 
moved down with other statements interposed, while '@b' is neither a 
statement nor expression but a def statement prefix, and is documented 
as such.

A dynamic difference between the constructs, as least with CPython, is 
that the decorator form does just one namespace binding instead of two.

> and in the latter case co_firstlineno points to the "def a()" line.
>
> Furthermore, co_firstlineno is an attribute of the code object, not the
> function object, so it shouldn't ideally depend on whether a decorator
> was applied or not.

Perhaps. A practical consideration is that it is easier to search 
forward from the first '@' line to the 'def' line than the reverse.

-- 
Terry Jan Reedy



More information about the Python-Dev mailing list