[Python-Dev] New relative import issue

Nick Coghlan ncoghlan at gmail.com
Tue Sep 19 12:16:59 CEST 2006


Josiah Carlson wrote:
> As it stands, in order to "work around" this particular feature, one
> would need to write a 'loader' to handle importing and/or main() calling
> in subpackage1/module1.py .

Yup. At the moment, you can rely on PEP 328, or an PEP 338, but not both at 
the same time. This was previously discussed back in June/July with Anthony 
convincing me that the solution to the current poor interaction shouldn't be 
rushed [1].

It is, however, pretty trivial to write a runpy.run_module based launcher that 
will execute your module and use something other than "__name__ == '__main__'" 
to indicate that the module is the main module. By letting run_module set 
__name__ normally, relative imports will "just work".

For example:

#mypkg/launch.py
# Runs a script, using the global _launched to indicate whether or not
# the module is the main module

if "_launched" not in globals():
     _launched = False
if (__name__ == "__main__") or _launched:
     import runpy
     # Run the module specified as the next command line argument
     if len(sys.argv) < 2:
         print >> sys.stderr, "No module specified for execution"
     else:
         del sys.argv[0] # Make the requested module sys.argv[0]
         run_module(sys.argv[0],
                    init_globals=dict(_launched=True),
                    alter_sys=True)

Cheers,
Nick.

[1] http://mail.python.org/pipermail/python-dev/2006-July/067077.html

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list