[Tutor] understanding __import__()

Sean Perry shaleh at speakeasy.net
Wed Jul 26 08:03:58 CEST 2006


Ok, this may be slightly above tutor's level, but hey, never hurts to 
ask (-:

I am playing with __import__().  Here is my code:
[code]
import os.path

app_path = '/tmp/my/settings'
app_path2 = 'my/settings'

if os.path.exists(app_path + '.py'):
     print "Found", app_path

try:
     f = __import__(app_path, globals(), locals(), [])
     print f.__name__, f.__file__
except Exception, e:
     print e

if os.path.exists(app_path2 + '.py'):
     print "Found", app_path2

try:
     f = __import__(app_path2, globals(), locals(), [])
     print f.__name__, f.__file__
except Exception, e:
     print e
[/code]

The result is the first import fails and the second one works. Even 
though they are the same file.

$ pwd
/tmp
$ ls
importer.py my/
$ ls my
settings.py
$ ./importer.py
Found /tmp/my/settings
No module named /tmp/my/settings
Found my/settings
my/settings /tmp/my/settings.py

What gives??


More information about the Tutor mailing list