[Tutor] How does this work?

Kent Johnson kent37 at tds.net
Wed Feb 7 12:06:56 CET 2007

Tony Cappellini wrote:
> I saw a snippet of python which is used to execute another python
> script, and I'm trying to understand the mechanism. Simple as it is, I
> don't understand how it works :-)

A few more points missed by Danny and Alan. Not to be taken as an 
endorsement of this strategy...

> this is the caller
> ##############################
> callee=open("tester.py").read()
> exec(callee)

I think these two lines could be written as

and exec is a statement, not a function, so you can write
exec callee

> So I looked a the docs for read() in the file module for a clue-
> didn't see anything obvious.

Hmm. You didn't find this?

> Also- I don't understand how the call to eval() executes "in the scope
> of" the main in tester.py. If  the main in the eval call were
> *somehow* qualified with something to provide scope to tester.py, It
> would probably make sense.

The exec is done in the scope of the caller as well, so the names 
defined in tester.py become names in the global namespace of the caller. 
You can provide optional parameters to both exec and eval() to change 
the namespace they use.


> Let's assume that the caller also has a main(). How does eval() know
> to execute main in the scope of tester.py, and not in the scope of the
> caller?

It doesn't. The main() in tester.py would replace the main() in the 
scope of the caller.
> This is pretty cool and confusing ;-)
> Is this a useful thing to do, or bad in practice?

Bad. There is usually a better way.

PS To import a file whose name is in a variable (string), see __import__().


More information about the Tutor mailing list