Relative path import problem for Python

Source: Internet
Author: User

Use Python as a project, if the project is large, or if you want to better manage the program, you always need the package. The package resolves the issue of naming conflicts.

Today, when using Python's relative path to import, there are a number of problems encountered.

Package Import Scenario:

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

If you want to reference the contents of functions.py in expander.py, this may mean

From.. Utilities Import functions.py

1. Error One: Valueerror:attemptedrelative Import beyond TopLevel Package

The problem is that the topmost layer of the package is reached, and the topmost layer is not a package.

Workaround: Add a directory mod to the main.py sibling, including components and utilities, and add a __init__.py to the MoD to resolve

See also: Http://stackoverflow.com/questions/4175534/relative-imports-in-python

2. Error Two: valueerror:attempted relative import in Non-package

Files that are imported using relative paths are no longer executed as master files. The reasons are as follows:

http://blog.csdn.net/chinaren0001/article/details/7338041

3. Error Three: No module named * * *

The module was not found under the specified path.

Relative path import problem for Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.