Hacker News new | ask | show | jobs
by Spivak 681 days ago
> Relative path imports are unnecessarily difficult, especially if you want to import something from a parent directory.

This is never explained well to beginners but this is because Python imports deal with modules and packages, any relationship with directories is accidental. With namespace packages foo.bar and foo.baz might live on totally separate parts of the filesystem. They might not live on the filesystem at all and instead be in a zip file.

    somedir/
    otherdir/
      __init__.py
      foo.py
    scripts/
      __init__.py
      myscript.py

    # in myscript.py
    from .. import otherdir.foo
If you `python scripts/myscript.py` then it won't work because myscript.py is run with a __name__ of __main__ which doesn't have any parent module.

When you run python -m scripts.myscript it sets __package__ to scripts.myscript so now it does have a parent module and somedir and otherdir are importable under the root module because '.' is added to the search path by default.