October 22, 2024
Chicago 12, Melborne City, USA
python

import that works from main module or directly


TL;DR How do I make an import resolvable regardless of whether a file is run directly or is itself imported by a parent module?

This is not the same as the million questions about importing modules from parent packages. I’ve had a hard time finding an exactly equivalent question, so if I’ve missed something, please point me in the right direction. On the other hand, maybe it means that what I’m trying to do doesn’t make sense.

I have a VSCode project based in pkg:

pkg\
    main.py
    __init__.py
    subpkg\
        foo.py
        bar.py
        __init__.py

Suppose foo.py contains something like this:

from bar import baz

def something_intended_to_be_called_from_main():
    baz()

def quick_and_dirty_tests_while_programming():
    pass

if __name__ == '__main__':
    quick_and_dirty_tests_while_programming()

And suppose that main.py just contains import foo.

Here’s the problem. If I run foo.py directly, the import is resolved. But if I run main.py, the import is not resolved because bar is not in pkg. I can address this by changing the import line in foo.py to from subpkg.bar import baz, but then it won’t be resolved when running it directly.

Is there a way to do what I’m trying to do? I mean, I guess I could put in a try ... except block with both resolutions, but that seems hackish (even more than including quick and dirty tests in submodules).



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video