MartyMacGyver MartyMacGyver - 1 year ago 59
Python Question

Importing a module in Python as part of a package *as well* as in a way that works stand-alone

Note: This is Python 3.5

Given some project

such that:

thing/ (imports bar)
utils/ (empty) (imports foo; has some functions and variables) (has some functions and variables)

I can
in, and when running the file must contain
to get to's code.

To run directly though, must have
import foo
instead (
fails). If I make that change then no longer works.

How can I run or and still use the same import construct in for both use cases? I feel like I'm missing some simple step or construct, but perhaps expecting to work independently in this way is asking too much (short of conditional imports or such).

Answer Source

Its typical to have all your entrypoints outside the module, than all imports can be relative. For example


And can look like

from thing import app
if __name__ == '__main__':

Than in you have

from .utils import bar

And in bar you have

from . import foo


from thing.utils import foo


from ..utils import foo

So if you need two entrypoints, you can either make app take a command line argument for the second entry point, or you can make another file like app that imports bar

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download