[Python-ideas] Prevent importing yourself?

Chris Angelico rosuav at gmail.com
Fri Jan 29 22:11:13 EST 2016


On Sat, Jan 30, 2016 at 11:13 AM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> In general though I think it's unfortunate that it's possible to be
> able to override installed or even stdlib modules just by having a .py
> file with the same name in the same directory as the running script. I
> had a discussion with a student earlier today about why '.' is not
> usually on PATH for precisely this reason: you basically never want
> the ls (or whatever) command to run a program in the current
> directory.
>

One solution would be to always work in a package. As of Python 3,
implicit relative imports don't happen, so you should be safe. Maybe
there could be a flag like -m that means "run as if current directory
is a module"? You can change to a parent directory and run "python3 -m
dir.file" to run dir/file.py; if "python3 -r file" could run file.py
from the current directory (and assume the presence of an empty
__init__.py if one isn't found), that would prevent all accidental
imports - if you want to grab a file from right next to you, that's
"from . import otherfile", which makes perfect sense.

It'd be 100% backward compatible, as the new behaviour would take
effect only if the option is explicitly given. Doable?

ChrisA


More information about the Python-ideas mailing list