Search code examples
python-3.xrelative-import

Python3 Relative Import Is not Working


I'm new in python 3. I'm trying to run lark examples http://github.com/lark-parser/lark in a development mode, but was blocked on relative import problem.

lark
  |examples
  |     |
  |     |conf_lalr.py
  |
  |lark
  |  |
  |  |lark.py
     |
     |tools
     |    |
          |common.py

In conf_lalr.py, there's a line: from lark import Lark Since I want use relative import, then I updated it with below methods:

1, from ..lark.lark import Lark

Traceback (most recent call last):
  File "conf_lalr.py", line 16, in <module>
    from ..lark.lark import Lark
ValueError: attempted relative import beyond top-level package

2, from .lark.lark import Lark

Traceback (most recent call last):
  File "conf_lalr.py", line 16, in <module>
    from .lark.lark import Lark
ModuleNotFoundError: No module named '__main__.lark'; '__main__' is not a package

I searched lots of answers from internet, including stackoverflow. However, none is working.

Need someone tell why.


Solution

  • You have missing init.py files to make the folders as python packages. Also for the first part , see this or this