On Sep 24, 8:37 am, David Cramer <[EMAIL PROTECTED]> wrote:
> I was digging through some code today, and I noticed imports are
> happening within a lot of functions. It was my knowledge that it works
> like so:
>
> import in a function is the same as ruby's load or php's include --
> its executed everytime the function is
>
> import in a module outside a function is like ruby's require or php's
> require_once -- its loaded and cached in memory

That's not the case. Try the following:

# importme.py
print "running importme"

def three():
  print "3 - from importme"

# test1.py
import importme
importme.three()

# test2.py
def one():
  import importme
  print "1"
  importme.three()

def two():
  import importme
  print "2"
  importme.three()

one()
two()

$ python test1.py
running importme
3 - from importme

$ python test2.py
running importme
1
3 - from importme
2
3 - from importme

As you can see, the initial print statement in importme.py only
executes once, even when "import importme" is run twice (from inside
functions).

As I understand it, Python's "import" statement checks sys.modules to
see if something has been imported already. If it hasn't, the module
is loaded for the first time and executed. If it has already been
imported (and hence is in sys.modules) then no extra code is loaded or
executed - the import statement merely ensures that a reference to
that module is available in the function's scope.

As a result the performance overhead from having imports inside
functions as opposed to at module level should be virtually non-
existent. I don't think we need to worry about this - and like Jeremy
said, usually there's a reason for doing it (avoiding importing
something unless it's actually going to be needed, or avoiding
circular imports).

Cheers,

Simon
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to django-developers@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to