Set toplevel for Python package -
okay, have below code in main application (main.py
)
from modules.core import core1 print core1.housenumber()
and below code in core1.py
:
from ..engine import engine1 def housenumber(): house = engine1.badluck() return house
also code in engine1.py
:
def badluck(): return 13
this work without problem, alright.
now, here interesting part, have below code in widget1.py
def door(): return 'black'
and code in core2.py
:
from ...widgets import widget1 def doorcolor(): door = widget1.door() return door
and if change main.py
to:
from modules.core import core1, core2 print core1.housenumber() print core2.doorcolor()
i error: attempted relative import beyond toplevel package
.
okay, if take main.py
out of projectx
in drive d
, change main.py
codes this:
from projectx.modules.core import core1, core2 print core1.housenumber() print core2.doorcolor()
it work perfectly.
okay, understand if from modules.core import core1, core2
means modules
top-level not projectx
even included __init__.py
to folder structure.
here question:
is there way can define toplevel folder in
main.py
without moving main file around?
note1: there solution adding full path like: from projectx.modules.core import core1
, from projectx.widgets import widget1
, it's not best solution,cause have sys.path.append()
, think there smart way.
note1: have done adding __all__
inside __init__.py
of projectx
:
__all__ = ['modules','widgets'] import modules import widgets
i didn't result.
include above example here download/study.
you don't need relative import in corex.py
files.
simply change core2.py
:
-from ...widgets import widget1 +from widgets import widget1
note: can refactor imports remove relative import.
diff --git a/modules/core/core1.py b/modules/core/core1.py index a0650fc..c6109e6 100644 --- a/modules/core/core1.py +++ b/modules/core/core1.py @@ -1,4 +1,5 @@ -from ..engine import engine1 +from modules.engine import engine1 + def housenumber(): house = engine1.badluck() - return house \ no newline @ end of file + return house diff --git a/modules/core/core2.py b/modules/core/core2.py index 2638734..b131d1f 100644 --- a/modules/core/core2.py +++ b/modules/core/core2.py @@ -1,4 +1,6 @@ -from ...widgets import widget1 +from widgets import widget1 + def doorcolor(): door = widget1.door() - return door \ no newline @ end of file + return door
Comments
Post a Comment