Python Forum
Relative import multiple levels ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Relative import multiple levels ?
#1
packages
- gradient
-- hsl_by_value.py
- objects
-- styles
--- box_style.py

How would I do? Like to do it with relative imports.
box_style.py
from ..gradient import hsl_by_value

I think I figure it out. So ... takes you to model name ?
from ...gradient import hsl_by_value
99 percent of computer problems exists between chair and keyboard.
Reply
#2
restate your structure. I dont understand what the dashes mean. From what i assume that means is?

packages/
    gradient/
        hsl_by_value.py
    objects/
        styles/
            box_style.py
Recommended Tutorials:
Reply
#3
This is how i would have done it.
my_pack\
|-- __init__.py
  gradient\
  |-- __init__.py
  |-- gradient.py
 
Top __init__.py is the file the file i change.
The use of .something or usage of __all__ in this __init__.py will prevent long imports for users.
A example of something that could have been done better Dodgy
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
__init__.py:
from .gradient import gradient
gradient.py:
def hsl_value():
    return 'rgb(255, 0, 0)'
So using my_pack look like this:
λ ptpython
>>> import my_pack
>>> my_pack.gradient.hsl_value()
'rgb(255, 0, 0)'

>>> # Or
>>> from my_pack import gradient
>>> gradient.hsl_value()
'rgb(255, 0, 0)'
Reply
#4
(Feb-02-2018, 08:23 PM)metulburr Wrote: restate your structure. I dont understand what the dashes mean. From what i assume that means is?

packages/
    gradient/
        hsl_by_value.py
    objects/
        styles/
            box_style.py

Yep. That what my structure looks like.
Thanks. The ... solved my problem.
99 percent of computer problems exists between chair and keyboard.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to reference the relative directory when creating a photoimage kenwatts275 3 6,201 May-18-2021, 07:22 PM
Last Post: menator01
  pyautogui screenshotting region relative to image found on screen Bmart6969 3 6,337 Oct-05-2019, 06:20 PM
Last Post: Bmart6969
  how do i write a cross-platform relative file path? pseudo 2 2,879 Aug-23-2019, 05:07 PM
Last Post: ThomasL
  function wanted: resolve relative path Skaperen 4 3,295 Sep-06-2018, 01:52 AM
Last Post: Skaperen
  Python 3.6.5 pathlib weird behaviour when resolve a relative path on root (macOs) QbLearningPython 7 6,098 May-29-2018, 08:38 AM
Last Post: QbLearningPython
  Parse XML - how to handle deep levels/hierarchy dwill 8 9,304 Apr-17-2018, 04:17 PM
Last Post: dwill
  ValueError: Attempted relative import in non-package JoeB 1 11,820 Mar-08-2018, 11:01 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020