Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

后端 未结 7 1303
灰色年华
灰色年华 2020-12-04 05:23

I have a directory structure similar to the following

meta_project
    project1
        __init__.py
        lib
            module.py
            __init__.py         


        
7条回答
  •  爱一瞬间的悲伤
    2020-12-04 05:59

    I had almost the same example as you in this notebook where I wanted to illustrate the usage of an adjacent module's function in a DRY manner.

    My solution was to tell Python of that additional module import path by adding a snippet like this one to the notebook:

    import os
    import sys
    module_path = os.path.abspath(os.path.join('..'))
    if module_path not in sys.path:
        sys.path.append(module_path)
    

    This allows you to import the desired function from the module hierarchy:

    from project1.lib.module import function
    # use the function normally
    function(...)
    

    Note that it is necessary to add empty __init__.py files to project1/ and lib/ folders if you don't have them already.

提交回复
热议问题