johhnry
johhnry

Reputation: 29

Python 3 : import module from top level package

I have this simple package structure with one module called ui:

test/
├── app.py
├── __init__.py
└── ui
    ├── __init__.py
    └── window.py

1 directory, 4 files

The window.py file contains a basic class :

# test/ui/window.py

class Window():
    def __init__(self):
        print("Window constructor")

and in my app.py I have :

# test/app.py

from ui import window

def run():
    w = window.Window()

Now in a Python 3 shell, I should be able to import the module app from the package test call the run function like this (I am in the parent directory of the package) :

>>> import test.app
>>> test.app.run()

However I get this error (with Python3) :

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test/app.py", line 1, in <module>
    from ui import window
ModuleNotFoundError: No module named 'ui'

Note that this works with Python2.7...

What is wrong here?

Upvotes: 1

Views: 293

Answers (1)

DestinyofYeet
DestinyofYeet

Reputation: 104

Tested in python 3.8

# test/app.py

from .ui import window


def run():
    w = window.Window()
>>> import test.app
>>> test.app.run()
Window constructor

You have to make a . infront of the ui to say that you are using a local folder. Since i don't know much about python 2 in general, i can't explain to you why its working there, but my best guess is, that they changed how to do relative imports in python 3

Upvotes: 1

Related Questions