简体   繁体   中英

Getting `Top `level package` error when importing module in `python3`

I am having directory structure as

-Practice
 -Connect
    -connect.py -> having function abc
    -__init__.py
 -Pytest
    -__init__.py
    -file.py

file.1 contents

from ..connect.connect import abc
abc()

Getting error as

ValueError: attempted relative import beyond top-level package

I can use import from parent directory as

from connect.connect import abc
abc()

This is working. Need to know why relative import is not working

As people suggested i have added init .py in Practice directory and still getting same error

您需要一个__init__.py位于顶级Practice文件夹中,因此 Python 知道它本身应该是一个包,而不是一个恰好包含两个包的随机文件夹。

You need an __init__.py in your Practice directory too. Otherwise, Pytest and Connect are separate toplevel packages and not sibling subpackages of the Practice package. Hence the error you're getting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM