[Python-ideas] Prevent importing yourself?

Andrew Barnert abarnert at yahoo.com
Fri Jan 29 22:23:01 EST 2016


On Jan 29, 2016, at 19:11, Chris Angelico <rosuav at gmail.com> wrote:
> 
> 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?

I like it.

The only problem is that people on platforms where you can add the -r on the shbang line will start doing that, and then their scripts won't be portable...

> 
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list