Wednesday, April 4, 2012

Guido views running scripts within a package as an anti-pattern


Imagine this directory structure:
app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py
I'm running mod1 (python app/sub1/mod1.py) and I need to import something from mod2. How should I do it?
I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package".
I googled around but found only "sys.path manipulation" hacks. Isn't there a clean way?

http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python


On 4/22/07, Brett Cannon wrote:
> This PEP is to change the ``if __name__ == "__main__": ...`` idiom to
> ``if __name__ == sys.main: ...``  so that you at least have a chance
> to execute module in a package that use relative imports.
>
> Ran this PEP past python-ideas.  Stopped the discussion there when too
> many new ideas were being proposed.  =)  I have listed all of them in
> the Rejected Ideas section, although if overwhelming support for one
> comes forward the PEP can shift to one of them.

I'm -1 on this and on any other proposed twiddlings of the __main__
machinery. The only use case seems to be running scripts that happen
to be living inside a module's directory, which I've always seen as an
antipattern. To make me change my mind you'd have to convince me that
it isn't.

-- 
--Guido van Rossum

http://mail.python.org/pipermail/python-3000/2007-April/006793.html

UPDATE:
Here is a good article by Nick Coghlan on Python import problems, which includes the case described above: https://ncoghlan_devs-python-notes.readthedocs.org/en/latest/python_concepts/import_traps.html

No comments:

Post a Comment