best way to ensure './' is at beginning of sys.path?

Steve D'Aprano steve+python at pearwood.info
Fri Feb 3 22:16:50 EST 2017


On Sat, 4 Feb 2017 10:13 am, Ben Finney wrote:

> 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>.

I think you are conflating the package directory and . the current working
directory. Relative imports do not, as far as I can see, have anything to
do with the current working directory.

I created these files in a directory under my home directory:


[steve at ando ~]$ ls test
eggs.py  spam.py
[steve at ando ~]$ cat test/eggs.py
pass
[steve at ando ~]$ cat test/spam.py
from . import eggs
print(eggs.__file__)


I cd'ed into the test folder, and tried running spam.py:

[steve at ando ~]$ cd test
[steve at ando test]$ python3.5 spam.py
Traceback (most recent call last):
  File "spam.py", line 1, in <module>
    from . import eggs
SystemError: Parent module '' not loaded, cannot perform relative import



So relative imports using . dot have nothing to do with importing from the
current directory.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list