David Tran
David Tran

Reputation: 47

Trouble understanding a strange Python import

I made this littlet test set up:

test\
    config.py
    run.py
    movie\
        __init__.py
        ironman.py
        impossible.py

I ran run.py from the test folder.

run.py:

import movie.ironman

ironman.py:

import impossible #okay
import config     #okay

What crazy is that both of those imports are good. Assuming that my path is relative to the test folder. I can understand how config.py was imported, however, how is impossible.py imported? Shouldn't it be movie.impossible instead?

I'm really bothered this and the import system in python is a bit confusing to me. It would be great if anyone can help me. Thank you in advance!

Upvotes: 2

Views: 67

Answers (1)

Daniel
Daniel

Reputation: 42758

Till Python 2.5 there was no real differentiation between relativ and absolute imports. Relative imports are relative to the current module, in your example movie. In newer python versions you can/have to import relative modules with a leading .:

import config
from .impossible import something

Here impossible is a module relative to the movie directory. And config is absolute to the search path, which also contains the directory of the calling program run.py.

Upvotes: 3

Related Questions