I have an application snork/Hello.py that has a child page snork/pages/1_Info.py and I would like them to import utility functions from a common snork/utils.py module. A relative import from Hello.py like from utils import load_graph works fine, but a similar import from 1_Info.py like from ..utils import load_graph fails with ImportError: attempted relative import with no known parent package.
I can update the path with sys.path.insert(1, os.path.realpath(os.path.pardir)) before the import, but that gets inserted every time the page runs. I can test to see if it’s there first, but that seems awkward, and maybe there’s a better way.
The load_graph() function is cached and pretty simple, there will be lots of other methods used in multiple pages:
Can you share the directory tree structure you have?
I have recreated to my best knowledge from your description below. Ensure that every directory has an __init__.py file to mark them as modules and allow relative imports.
I’m tried moving utils.py into the pages directory and replacing the import in Hello.py to from pages.utils import load load_graph which works, but then utils shows up as a page. I tried renaming it to _utils.py thinking it’ll skip the page, but it still shows it (blank, of course). I tried replacing pages/__init__.py with utils.py and in Hello.py from pages import load_graph works, but in 1_Info.py from __init__ import load_graph doesn’t work.
I’ll stick to the “humph” and update sys.path until there’s a canonical solution.
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.