import's recursion
Duncan Booth
duncan at NOSPAMrcp.co.uk
Fri Dec 6 04:43:48 EST 2002
mailspamforme at yahoo.com (_rui_) wrote in
news:2d9b77f4.0212052022.405d2813 at posting.google.com:
> hi, list!
> Tell me please, why recursion is absent?
>
>
> foo.py
> ~~~~~~
> import foo
>
This is what happens:
You run the script foo.py, this creates a module called '__main__',
compiles the code into it, executes the code.
The code in module __main__ executes 'import foo':
Looks in sys.modules for a module called foo.
There isn't one so:
Finds foo.py
Compiles foo.py into foo.pyc
Creates a new module 'foo' containing the foo code.
Stores a reference to module foo in sys.modules
Starts to execute module 'foo'.
The code in module foo executes 'import foo':
Looks in sys.modules for a module called foo.
Finds one and returns it:
Sets the variable foo.foo to module foo
Module foo has finished executing.
__main__.foo is set to module foo
In short imports aren't recursive because attempting to import a module
that is partly imported gives you a reference to the module but doesn't
attempt to reexecute the code it contains. This means you may get a
reference to a module that doesn't yet contain any functions or classes,
but that isn't a problem so long as you dont attempt to reference them
until later when all the imports have completed.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list