简体   繁体   中英

Value Error: Attempted relative import beyond top-level package

I have been creating an application that will run just like Microsoft Notepad . My program comprises of the following file and folder:

libs (Folder)
scripts (Folder)
test.py

The test.py is the file in which I am trying the following code:

from .libs import tkinter
from .libs import pyglet
from .libs import threading

test_window = Tk()

test_window.mainloop()

In the folder libs I have added the modules that are required in the application. Example: Tkinter, Pyglet and Threading

When I am trying to import them into test.py using the code above and then running the program. I see the following Traceback:

Traceback (most recent call last):
  File "c:\Users\Bhavyadeep\Desktop\NuclearPad\test.py", line 1, in <module>
    from .libs import tkinter
ImportError: attempted relative import with no known parent package

I don't really know how I solve this problem. Is it because I added the module in the folder where Import in not available? Or is it because I did something wrong in this module folder copying-pasting to a folder not at Python's PATH ?

from .libs import tkinter

Means "import tkinter from the package called lib which is located in the same directory as file (this script)"

so your first line should say something like

test_window = tkinter.Tk()

unless you use either of the following:

from .libs.tkinter import *
from .libs.tkinter import Tk

The error is likely due to you using relative import syntax from within the script you are trying to execute. Remove the leading dots in order to execute test.py , otherwise append its directory to sys.path or use site.addsitedir(path_to_directory_containing_test_py) and import it as follows import test .

With that said, you should not call the module's file test.py because there is already something with that name in python's default Lib directory or builtins. If you insist, there should be a hacky way to get it done without changing the name through importlib.

As for why this error occurs, I think it's because the interpreter is designed to execute scripts but not modules/packages whose contents are placed in.pyc files in __pycache__ s when imported.


In order to import from scripts or libs , they must be packages. In order to turn them into packages you must add __init__.py files to them.


Lastly, It's a pretty terrible idea to place third-party libraries in your source like this. At the very least you should have installed them properly on your machine and then copied their sources from site-packages /the equivalent for venv s, which will fail if they use any executables and/or have any external dependencies

Documentation for distributing python packages

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