[Python-ideas] Security: remove "." from sys.path?

Chris Angelico rosuav at gmail.com
Thu Jun 1 12:46:47 EDT 2017


On Fri, Jun 2, 2017 at 2:30 AM, Victor Stinner <victor.stinner at gmail.com> wrote:
> Perl 5.26 succeeded to remove the current working directory from the
> default include path (our Python sys.path):
>
> https://metacpan.org/pod/release/XSAWYERX/perl-5.26.0/pod/perldelta.pod#Removal-of-the-current-directory-(%22.%22)-from- at INC
>
> Would it technically possible to make this change in Python? Or would
> it destroy the world? Sorry, it's a naive question (but honestly, I
> don't know the answer.)

(AIUI, the *current directory* is never on Python's path, but the
*script directory* is. They're the same thing a lot of the time.)

All it'd take is one tiny change to Python, and then one tiny change
to any multi-file non-package Python app.

1) Make the script directory implicitly function as a package. In
effect, assume that there is an empty __init__.py in the same
directory as the thing you just ran.

2) Any time a Python app wants to import from its own directory, it
needs to "from . import blah" instead of simply "import blah".

Then the removal you suggest could be done, without any loss of
functionality. The change could alternatively be done as an import
hack rather than an actual fake package if that's easier, such that
"from . import blah" means either "import from the script directory"
or "import from the current package" as appropriate.

Or, it could be more simply done:

1) Make script-directory-local imports raise a warning, citing
packages as the best solution.

IMO it's a logical extension to relative imports, and a good solution
to the "Idle crashes on startup" problem that comes from someone
creating a "random.py" in the current directory.

Big +1 from me for this.

ChrisA


More information about the Python-ideas mailing list