This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author ncoghlan
Recipients ncoghlan
Date 2017-03-28.09:22:29
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1490692950.43.0.231452338576.issue29929@psf.upfronthosting.co.za>
In-reply-to
Content
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).
History
Date User Action Args
2017-03-28 09:22:30ncoghlansetrecipients: + ncoghlan
2017-03-28 09:22:30ncoghlansetmessageid: <1490692950.43.0.231452338576.issue29929@psf.upfronthosting.co.za>
2017-03-28 09:22:30ncoghlanlinkissue29929 messages
2017-03-28 09:22:29ncoghlancreate