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
  Designing Game Levels (Very Basic) Hudjefa 0 576 Sep-01-2024, 06:41 AM
Last Post: Hudjefa
  import a function from another file using relative path paul18fr 6 3,141 Aug-01-2024, 06:40 AM
Last Post: paul18fr
  How to reference the relative directory when creating a photoimage kenwatts275 3 9,407 May-18-2021, 07:22 PM
Last Post: menator01
  pyautogui screenshotting region relative to image found on screen Bmart6969 3 8,402 Oct-05-2019, 06:20 PM
Last Post: Bmart6969
  function wanted: resolve relative path Skaperen 4 4,423 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 8,120 May-29-2018, 08:38 AM
Last Post: QbLearningPython
  Parse XML - how to handle deep levels/hierarchy dwill 8 13,621 Apr-17-2018, 04:17 PM
Last Post: dwill
  ValueError: Attempted relative import in non-package JoeB 1 13,858 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