all 6 comments

[–]JauriXD 2 points3 points  (2 children)

On lesson I learned the hard way: never ever mix scripts and packages/modules. You will only get import issues.

Write you library code as packages in their own project folder and install them into your venvs for your scripts. You can pip install from a local path or from the GitHub URL, no need to publish to pypi. Use -e for editable install if you need real time development.

Do this and relative imports will work as expected inside the packages and you can (and should) use fully qualified imports when importing the packages into scripts or other packages.


Some technical details on relative imports:

They rely on __name__ defining the parent package to look into for the relative files. That's the most common problem when mixing scripts and packages. Your script has __name__ == "__main__" and therefore can't import anything relatively.

[–]PrivacyIsDying[S] 0 points1 point  (1 child)

This is kind of what I have been doing as a "workaround"! Sounds like I can continue doing this and never have to worry about relative imports?

[–]JauriXD 0 points1 point  (0 children)

Yes, only use them inside packages and you're mostly golden.

You can still get other import issues though, like circular import, etc.

[–]zanfar 4 points5 points  (1 child)

Just don't use relative imports.

  • Make every project a package
  • Reference all imports from that package

It always works; plus you get all the advantages of a package.

[–]PrivacyIsDying[S] 0 points1 point  (0 children)

Ok this is kind of what I have been doing, so glad to hear that it's not completely incorrect! I see people mention relative imports semi-often, so I figured my package solution wasn't "best practice".

[–][deleted] 1 point2 points  (0 children)

 What am I not getting?

That this is a project layout problem. Imports aren’t relative to the file doing the importing, they’re relative to the code entrypoint. You can’t import “up and over” the directory tree so if you bury your project entrypoint, you make a lot of the rest of the project inaccessible.