views:

269

answers:

3

hi,

I have the Python modules a.py and b.py in the same directory. How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? This module will be distributed so I can't hardcode a single path.

I've been playing around with __file__, sys.path and os.chdir, but it feels messy. And __file__ is not always available.

thanks

+6  A: 

Actually, __file__ is available for an imported module, but only if it was imported from a .py/.pyc file. It won't be available if the module is built in. For example:

>>> import sys, os
>>> hasattr(os, '__file__')
True
>>> hasattr(sys, '__file__')
False
Ned Batchelder
+1  A: 

Using the inspect module will make the builtin modules more obvious:

>>> import os
>>> import sys
>>> inspect.getfile(os)
'/usr/local/lib/python2.6/os.pyc'
>>> inspect.getfile(sys)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/inspect.py", line 407, in getfile
    raise TypeError('arg is a built-in module')
TypeError: arg is a built-in module
jls
A: 

Put the directory that contains both in your python path... or vice versa.

phillc
that's what I'm trying to do with sys.path...
Plumo