[Python-ideas] Pseudo-package for current directory
Terry Reedy
tjreedy at udel.edu
Mon Mar 7 17:59:55 EST 2016
On 3/7/2016 12:22 PM, Chris Angelico wrote:
> In theory, though, since it doesn't change syntax, it could be something like:
>
> import sys
> sys.package_mode_ACTIVATE()
>
> The trouble is that doing this after _any_ imports (including the ones
> that are done before your script starts) will risk those imports being
> resolved from local files.
Barring a setting in $PYTHONPATH, Python's startup imports will not be
resolved from local files. It appears that '' or scriptdir are only
added to sys.path afterwards. I base this on an experiment where I
tried to shadow one of the Python-coded /lib modules with a local file.
C-coded builtin modules cannot be shadowed. I discovered this by
experiment and then found
"Python includes a number of default finders and importers. The first
one knows how to locate built-in modules, and the second knows how to
locate frozen modules. A third default finder searches an import path
for modules. The import path is a list of locations that may name file
system paths or zip files."
https://docs.python.org/3/reference/import.html#finders-and-loaders
I consider the behavior of local versus stdlib imports depending on the
stdlib implementation language to be somewhat problematical. There was
discussion of shadowing, I believe here, a few months ago (sometime
after 3.5.0 was released).
> Having "import X" after activating package
> mode is useless if X gets resolved from sys.modules, and it'd be a
> nightmare to debug.
>
> If the -p parameter is a problem, maybe there could be an environment
> variable that changes the default? Then people could opt-in to
> pseudo-package mode globally, run all their tests, and see what stops
> working.
>
> FWIW, I do want this to eventually become the default behaviour. But
> it wouldn't be any time soon; in the meantime, it would be easy enough
> to recommend that people just "always do this to be safe" (in the same
> way that Python 2 didn't make new-style classes the default, but
> everyone's advised to "always subclass object"). By making it a
> long-term non-default feature, Python gets to provide safety without
> breaking anyone's code.
You might want to look at previous discussions of shadowing if you can
find them.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list