[Tutor] function declaration problems perhaps?

Kent Johnson kent37 at tds.net
Wed Jul 25 20:14:48 CEST 2007


Alan Gauld wrote:
> "Kent Johnson" <kent37 at tds.net> wrote
>> scripts. However this has no bearing on the current thread; for both
>> imported modules and executed scripts, a function must be defined 
>> before
>> it can be called.
> 
> Yes, the bearing is in the way that Perl compiles its code.
> Perl builds a name tree from the entire file before executing
> so it doesn't rely on the order of definition, Python seems
> to compile and execute code in a sequential manner and
> therefore relies on the sequence being right.

It executes code in a sequential manner, and names are bound during 
execution, not compilation. That is the key difference. I guess you 
could say that the compiler doesn't forward any names to the execution 
phase; when a module starts executing, the only names in the module 
namespace are
['__builtins__', '__doc__', '__file__', '__name__']

You can see this if you import a module whose contents are just
print dir()

Any other names must be bound by executing code.

> I'm not sure if the undefined name errors come from the compilation
> or from the execution - does anyone else. I confess i've never looked
> deeply into how Python actually does its complile/execute cycle.

They come from execution. See my separate post about def, etc. being 
executable statements.

Kent


More information about the Tutor mailing list