Python custom module not found inside an example folder

I'm working in a python project where I'm developing a custom lib (mylib) and using vscode.

/
└── mylib
    └── __init__.py
    ├── ...

If my program split_example.py is on the root, like below, I'm able to import and use mylib.

/
└── mylib
    └── __init__.py
    ├── ...
└── split_example.py

I would like to create a folder called examples and use mylib, but inside the folder examples I'm not able to import and use mylib.

/
└── mylib
    └── __init__.py
    ├── ...
└── examples
    └── split_example.py

Getting the following error:

Traceback (most recent call last):
  File "/home/kleysonr/.vscode/extensions/ms-python.python-2019.11.50794/pythonFiles/ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "/home/kleysonr/.vscode/extensions/ms-python.python-2019.11.50794/pythonFiles/lib/python/old_ptvsd/ptvsd/__main__.py", line 432, in main
    run()
  File "/home/kleysonr/.vscode/extensions/ms-python.python-2019.11.50794/pythonFiles/lib/python/old_ptvsd/ptvsd/__main__.py", line 316, in run_file
    runpy.run_path(target, run_name='__main__')
  File "/usr/lib/python3.6/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "/usr/lib/python3.6/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/data/dev/python/myproject/examples/split_example.py", line 3, in <module>
    from mylib.dataset import split
ModuleNotFoundError: No module named 'mylib'

What should I do to have any program inside the folder examples able to from mylib.dataset import split ?

1 answer

  • answered 2019-12-09 13:35 Kleyson Rios

    Based on the @fabioconcina comment, I found this solutions.

    Just include the following on the top of the file:

    from os import sys, path
    PARENT_DIR = path.dirname(path.dirname(path.abspath(__file__)))
    sys.path.append(PARENT_DIR)