[Tutor] question about where to import

Sean 'Shaleh' Perry shalehperry@attbi.com
Mon, 01 Apr 2002 19:33:42 -0800 (PST)


> 
> If this is not just some laziness on the part of the tutorial-writer 
> (and I'm not saying it is!), then can someone just explain why you would 
> do it this way and not just import once at the top of the script -- if I 
> am not mistaken, these functions should be available to any instance of 
> the class if it is done this way too.
> 

as always a test script helps:

foo.py:

#!/usr/bin/python

class Foo:
  def __init__(self):
    print "Foo being constructed"

  def do_it(self):
    import bar
    b = bar.Bar()
    print b

for i in range(1, 5):
  f = Foo()
  print f

for i in range(1, 5):
  f = Foo()
  f.do_it()

bar.py:

class Bar:
  def __init__(self):
    print "Bar being constructed"

print "bar being imported"

when I run it:

./foo.py 
Foo being constructed
<__main__.Foo instance at 0x8057b7c>
Foo being constructed
<__main__.Foo instance at 0x808a6c4>
Foo being constructed
<__main__.Foo instance at 0x8057b7c>
Foo being constructed
<__main__.Foo instance at 0x808a5ec>
Foo being constructed
bar being imported
Bar being constructed
<bar.Bar instance at 0x805862c>
Foo being constructed
Bar being constructed
<bar.Bar instance at 0x80595bc>
Foo being constructed
Bar being constructed
<bar.Bar instance at 0x808a6cc>
Foo being constructed
Bar being constructed
<bar.Bar instance at 0x80595bc>

note the import only happens the first time the method is called.  If the
method is never called, the import never happens.  If the method is called
many, many times it is only imported once.