|Title:||Delineation of the main module|
|Last-Modified:||2007-06-19 04:20:07 +0000 (Tue, 19 Jun 2007)|
This PEP has been rejected. Guido views running scripts within a package as an anti-pattern  .
Because of how name resolution works for relative imports in a world where PEP 328 is implemented, the ability to execute modules within a package ceases being possible. This failing stems from the fact that the module being executed as the "main" module replaces its __name__ attribute with "__main__" instead of leaving it as the absolute name of the module. This breaks import's ability to resolve relative imports from the main module into absolute names.
In order to resolve this issue, this PEP proposes to change how the main module is delineated. By leaving the __name__ attribute in a module alone and setting sys.main to the name of the main module this will allow at least some instances of executing a module within a package that uses relative imports.
This PEP does not address the idea of introducing a module-level function that is automatically executed like PEP 299 proposes.
With the introduction of PEP 328 , relative imports became dependent on the __name__ attribute of the module performing the import. This is because the use of dots in a relative import are used to strip away parts of the calling module's name to calculate where in the package hierarchy an import should fall (prior to PEP 328 relative imports could fail and would fall back on absolute imports which had a chance of succeeding).
For instance, consider the import from .. import spam made from the bacon.ham.beans module ( bacon.ham.beans is not a package itself, i.e., does not define __path__ ). Name resolution of the relative import takes the caller's name ( bacon.ham.beans ), splits on dots, and then slices off the last n parts based on the level (which is 2). In this example both ham and beans are dropped and spam is joined with what is left ( bacon ). This leads to the proper import of the module bacon.spam .
This reliance on the __name__ attribute of a module when handling relative imports becomes an issue when executing a script within a package. Because the executing script has its name set to '__main__' , import cannot resolve any relative imports, leading to an ImportError .
For example, assume we have a package named bacon with an __init__.py file containing:
from . import spam
Also create a module named spam within the <