[Tutor] understanding __import__()

Kent Johnson kent37 at tds.net
Wed Jul 26 12:44:36 CEST 2006


Sean Perry wrote:
> 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.
>   
The first argument to __import__ should be a module or package name, not 
a file path, e.g. "my.settings". Python will look for the module in the 
current sys.path the same as if you used a normal import. Apparently the 
/ is being interpreted as a . and I guess you have a file my/__init__.py so
  import my.settings
will work but
  import .tmp.my.settings
doesn't.

Kent
> $ 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??
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   




More information about the Tutor mailing list