[Tutor] Expression order problem

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu May 26 21:23:08 CEST 2005



On Thu, 26 May 2005, William O'Higgins wrote:

> I am running into problems with script evaluation order - specifically,
> the Python interpreter seems to read and execute scripts line by line.

Hi William,


Ah!  This happens to me too; one common idiom to avoid definition-order
issues like this is to create some central main() function:

######
def main():
    ...
######


and then, at the very bottom of the file, add a bit of code to start
things up:

######
if __name__ == '__main__':
    main()
######

The reason this works is because main() is called only after all the other
definitions are in place.  That is, we start things up only after the name
bindings are done.



> This is a problem if you are used to Perl, where the whole script is
> parsed first (Perl also auto-vivifies variables, but that's a different
> problem for a different day).

Perl does do that first pass to collect symbols, but it can also be
fraught with gotchas.  For example, the Perl code here:

### Perl ###
print count(), "\n";
print count(), "\n";
print count(), "\n";

{ my $x = 42;
  sub count {
      $x++;
      $x;
  }
}
######

exposes a similar kind of gotcha with evaluation order.


It's usually best to avoid the situation altogether, and get the
definitions in front first.  Using the "main()/if __name__ == '__main__'"
idiom is one way to avoid the definition sequence issues.


Best of wishes!



More information about the Tutor mailing list