简体   繁体   中英

Import error with unit tests: “No module named …” from local libary

I'm new to Python (JS developer) and am trying to run a testing suite. My project folder structure is as such:

project/
  __init__.py
  libs/
    __init__.py
    s3panda.py 
  tests
    __init__.py
    tests_s3panda.py

In terminal, I'm running python tests_s3panda.py .

I don't understand how it's unable to find a local module:

Traceback (most recent call last): File "tests_s3panda.py", line 7, in from libs.s3panda import S3Panda ImportError: No module named libs.s3panda

tests_s3panda.py snippet:

from __future__ import absolute_import

import unittest

import pandas as pd

from libs.s3panda import S3Panda


class TestS3Panda(unittest.TestCase):
    ...

Doing from ..libs.s3panda import S3Panda for relative path, I get:

ValueError: Attempted relative import in non-package

I believe the fact that there is no init.py in the top-level folder means that Python is not aware that libs and tests are both part of the same module called project .

Try adding an __init__.py to your project folder, then write the import statement as from project.libs.s3panda import S3Panda . In general, you want to specify absolute imports rather than relative imports ( When to use absolute imports ).

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