Execution of import (was Re: boolean xor)

Tim Peters tim.one at home.com
Sun Jan 7 23:43:00 EST 2001


> def xor(a,b):
>     from operator import truth
>     return truth(a) ^ truth(b)

[Peter Hansen]
> An aside: does the 'from .. import' statement  execute every time
> the function 'xor' is called, or only during the execution
> of the 'def' statement?

Every stmt in Python is executable except for "global", and every executable
stmt executes where it looks like it should <wink>.  "from" is the same as
"x=1" in those respects (for that matter, so are "def" and "class").  So,
yes, every time 'xor' is called.  But imported modules are cached in
sys.modules, so anything that imports module X will cause X to get
*executed* only if it's the first time X is imported (by anything) during
the program run.  Imports of X after the first are just lookups, mapping the
module name to the (already executed) module object and retrieving the
latter.

blazingly-fast-ly y'rs  - tim





More information about the Python-list mailing list