Python Forum

Full Version: Relative import multiple levels ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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
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)'
(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.