Search code examples
pythondirectorystructure

Import functions from a different directory where those files only contain that one function each


I currently have a directory structure like:

project/
  indicators/
    __init.py__ (contains __all__ = ['ATR', 'MACD'])
    ATR.py
    MACD.py
  strategies/
    strategy.py

in ATR.py and MACD.py I have a function like:

def ATR(dataframe, period):
  # do math

From strategy.py I can do:

from indicators.ATR import ATR

ATR(dataframe, period)

or

from indicators import *

ATR.ATR(dataframe, period)

but I would like to do something like

from indicators import ATR, MACD

ATR(dataframe, period)
MACD(dataframe, period)

What is the proper way to set up this structure? I think I need a way to specify some sort of "default" export in each of the indicators/.


Solution

  • In the __init__.py add, before your __all__ list:

    from ATR import ATR
    from MACD import MACD
    

    This will affect the other imports you don't like, but I think you will be able to see that you can manage what exactly is a name you are exporting, to your likings, inside __init__.py.