Why Does Import Of Sibling Packages Not Always Work In Python: On ‘attempted relative import beyond top-level package’

  • 1 main file
  • multiple subfolders that refer to each other
attempted relative import beyond top-level package
  • the current working directory (CWD) is not a package
  • you need a folder within the current working directory containing the main.py ()
  • this folder, the top-level package can be called something like .\packages but it can have other names, too
  • you cannot easily refer from top-level package to main.py, other modules within CWD, or to other top-level packages within CWD
  • I believe there are hacks, but why?
  • for example, in C# it is conventional to have src for code and test for tests as siblings
  • the CWD in Python does not work as a package — therefore you can’t refer from first-level subfolders across each other
  • this is officially explicitly discouraged
  • but there is demand — even bounty is given to the solution on Stack Overflow
  • in essence, there is a big difference between
  1. running a Python file
  2. importing that file from somewhere else
  • knowing what directory a file is in does not determine what package Python thinks it is in.
  • that depends on how you load the file into Python (by running or by importing)
  • essential: if __name__ does not contain . it is not considered to be a part of the package
  • it, therefore, is not important where it is on the disk
  • if I navigate to the ./runner subfolder and call python real_run.py the situation changes:
  • module make_change.py will NOT be able to call logger.py because they become siblings, i.e. 2 top-level packages

3. LINKS

--

--

--

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Moving to TCPStream, Bye Tokio!

Complete Guide to Terraform: News, Updates, Tips

Baby Rudin Ch. 2: Basic Topology

How to Become A Game Tester? |Tutorial &Beginner’s Guide of Game Testing (2)

The role and main work of game tester in a game development team.

Victory! Overcoming Programming Challenges

Hosting a Decentralized Application for Free with GitHub Pages

Special collaboration with bRing!

Publishing, Discovering, and Running Machine Learning Models with DLHub

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

More from Medium

The Parameters And Usage Of Ranges In Python

Datetime Function in Python

Python code Formatting with Black

Python Memory Management