[New-bugs-announce] [issue29929] Idea: Make __main__ an implied package

Nick Coghlan report at bugs.python.org
Tue Mar 28 05:22:30 EDT 2017


New submission from Nick Coghlan:

In just the last 24 hours, I've run across two cases where the default "the script directory is on sys.path" behaviour confused even experienced programmers:

1. a GitHub engineer thought the Python version in their Git-for-Windows bundle was broken because "from random import randint" failed (from a script called "random.py"

2. a Red Hat engineer was thoroughly confused when their systemd.py script was executed a second time when an unhandled exception was raised (Fedora's system Python is integrated with the ABRT crash reporter, and the except hook implementation does "from systemd import journal" while dealing with an unhandled exception)

This isn't a new problem, we've known for a long time that people are regularly confused by this, and it earned a mention as one of my "Traps for the Unwary in Python's Import System": http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html#the-name-shadowing-trap

However, what's changed is that for the first time I think I see a potential way out of this: rather than injecting the script directory as sys.path[0], we could set it as "__main__.__path__ = [<the-script-dir>]".

Cross-version compatible code would then be written as:

    if "__path__" in globals():
        from . import relative_module_name
    else:
        import relative_module_name

This approach would effectively be a continuation of PEP 328 (which eliminated implicit relative imports from within packages) and PEP 366 (which allowed implicit relative imports from modules executed with the '-m' switch).

----------
components: Interpreter Core
messages: 290689
nosy: ncoghlan
priority: normal
severity: normal
status: open
title: Idea: Make __main__ an implied package
type: enhancement
versions: Python 3.7

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue29929>
_______________________________________


More information about the New-bugs-announce mailing list