best way to ensure './' is at beginning of sys.path?
Ben Finney
ben+python at benfinney.id.au
Fri Feb 3 18:13:50 EST 2017
Neal Becker <ndbecker2 at gmail.com> writes:
> I want to make sure any modules I build in the current directory
> overide any others. To do this, I'd like sys.path to always have './'
> at the beginning.
The ‘sys.path’ list is used only for *absolute* imports. Modules in the
current directory should not be imported with an absolute path[0]. So, the
current directory should not be in ‘sys.path’.
So, for the past ten years and more, Python supports import of modules
from the current directory with an explicit *relative* path::
# Absolute imports, searching ‘sys.path’.
import datetime
from collections import namedtuple
# Relative imports, starting from this module's directory.
from . import foo
from .bar import baz
See <URL:https://www.python.org/dev/peps/pep-0328/>, in particular
<URL:https://www.python.org/dev/peps/pep-0328/#guido-s-decision>.
[0]: Why not? See the rationale for forcing absolute import by default
<URL:https://www.python.org/dev/peps/pep-0328/#rationale-for-absolute-imports>,
“[I]t is not clear whether ‘import foo’ refers to a top-level
module or to another module inside the package.[…] It's a
particularly difficult problem inside packages because [without
explicit relative import syntax] there's no way to specify which
module is meant.”
--
\ “True greatness is measured by how much freedom you give to |
`\ others, not by how much you can coerce others to do what you |
_o__) want.” —Larry Wall |
Ben Finney
More information about the Python-list
mailing list