variable declaration

Alex Martelli aleaxit at yahoo.com
Tue Feb 8 03:04:10 EST 2005


Terry Reedy <tjreedy at udel.edu> wrote:

> "Brian van den Broek" <bvande at po-box.mcgill.ca> wrote in message 
> news:4208178F.40804 at po-box.mcgill.ca...
> > Is the right way to understand it in this vicinity:
> 
> In the vicinity, but not quite exact
> 
> >At compile time (by which I mean when the Python bytecode is built)
> 
> Compile time is when the def statement is executed

I disagree: compile time is when the compiler is running (for example,
the compiler is the component which diagnoses syntax errors, while other
errors are diagnosed ``at runtime'').

Bytecode is built before def executes -- indeed it's built whether def
executes or not.  Cfr:

>>> def f(wo):
...   if wo:
...     def g(): pass
... 
>>> f.func_code.co_consts
(None, <code object g at 0x382a60, file "<stdin>", line 3>)

the 'def g' hasn't executed (yet?), but the bytecode is built (and
stored as the first constantvalue in f, save the ubiquitous None).

If the ``if wo: def ...'' construct was in a module being imported, the
mechanics would be similar -- although in this case I think you could
tell only if a syntax error was present in the def statement (I may be
wrong, but offhand I don't think the codeobject is saved in this case).

Or, try this one:

>>> c = compile('def x(): pass', '<string>', 'exec')
>>> c
<code object ? at 0x389420, file "<string>", line 1>
>>> c.co_consts
(<code object x at 0x3893e0, file "<string>", line 1>, None)
>>> 

``compile time'' here is when the 'compile' built-in runs; and we can
see the code object ``x'' is already built even though the def has not
been executed yet.


Alex



More information about the Python-list mailing list