Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative imports in Python

Hey all -- I am pulling my hair out with relative imports in Python. I've read the documentation 30 times and numerous posts here on SO and other forums -- still doesn't seem to work.

My directory structure currently looks like this

src/     __init__.py     main.py     components/         __init__.py         expander.py         language_id.py     utilities/         __init__.py         functions.py 

I want expander.py and language_id.py to have access to the functions module. I run python main.py which accesses the modules just fine with from components.expander import * and components.language_id import *.

However, the code inside expander and language_id to access the functions module:

from ..utilities.functions import * 

I receive this error:

ValueError: Attempted relative import beyond toplevel package 

I have gone over it a bunch of times and it seems to follow the documentation. Anyone have any ideas of what's going wrong here?

like image 623
apexdodge Avatar asked Nov 14 '10 00:11

apexdodge


People also ask

What are relative imports in Python?

A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is. There are two types of relative imports: implicit and explicit. Implicit relative imports have been deprecated in Python 3, so I won't be covering them here.

Should I use relative or absolute imports Python?

Note that relative imports are based on the name of the current module. Since the name of the main module is always “main”, modules intended for use as the main module of a Python application must always use absolute imports.

What are the imports in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.


1 Answers

Nevermind, I solved it:

src/     main.py     mod/         __init__.py         components/             __init__.py             expander.py             language_id.py         utilities/             __init__.py             functions.py 

main.py then refers to the subpackages as:

from mod.components.expander import * from mod.utilities.functions import * 

expander.py and language_id.py have access to functions.py with:

from ..utilities.functions import * 

But the interesting thing is that I had a text file inside the components directory that expander.py uses. However, at runtime it couldn't locate the file even though it was in the same directory. I moved the text file to the same directory as main.py and it worked. Seems counter-intuitive.

like image 150
apexdodge Avatar answered Sep 30 '22 12:09

apexdodge