python importing relative modules
-
06-07-2019 - |
Question
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
Solution
Put the directory that contains both in your python path... or vice versa.
OTHER TIPS
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
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow