On 11/07/13 05:02, Jim Mooney wrote:

The question is - does importing into a function
ever make sense? It  occurred to me that if you use    from module
import * , putting it in a function protects you from invisible
namespace pollution by a big module with a lot of names. But importing
has to be a big overhead. So does importing into a function make sense
at any time, or is it a dead end?

It's not encouraged, but it's not prohibited either.

Imports are very expensive the first time you do them, but after that they are cached and 
are quite fast. There's a long-term cache on disk (the .pyc file) and a short-term cache 
in memory (inside sys.modules). "import module" looks something like this 
pseudo-code:

if "module" in sys.modules:
    module = sys.modules["module"]
    return
for directory in sys.path:
    if there are both "module.py" and "module.pyc" files in
    the directory, and "module.pyc" is newer than "module.py",
    or there is only "module.pyc":
        module = load("module.pyc")
        break
    elif there is only a "module.py" file:
        module = compile("module.py")
        try:
            write file "module.pyc"  # on-disk cache
        except:
            pass
        break
if no module found:
    raise ImportError
sys.modules["modules"] = module  # memory cache cache
return


only the real code is much, much more complex. But the end result is that 
importing is only slow the first time.

Why might you put an import inside a function? The main reason is to delay a 
circular import. Suppose you have a module X that relies on Y, and Y relies on 
X. That's tricky to do: X can't import until Y is imported, and Y can't import 
until X is imported. But if X can delay importing Y until X's functions are 
called, it will work out fine.



--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to