2

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

user3871
  • 12,432
  • 33
  • 128
  • 268

1 Answers1

1

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).

  • didn't include it before in the question, but `__init__.py` has always existed in the project folder. Also, the URL you linked states that relative imports are okay as of PEP8 (2013) – user3871 Nov 13 '17 at 23:40
  • Ok, it could be that the problem is you need to set your PYTHONPATH then. Run `export PYTHONPATH=X:$PYTHONPATH`, replacing X with the parent directory of the `project ` folder. Then try it with the absolute import. Also, sorry, that was a hastily copied link. But check out the Google Python Style Guide (https://google.github.io/styleguide/pyguide.html#Imports) or PEP8 (https://www.python.org/dev/peps/pep-0008/#imports). Most people will probably recommend that you use absolute imports just to avoid confusing yourself. – Justin Payan Nov 14 '17 at 00:16
  • Oh I see the quote you're mentioning in my link is actually from PEP8 itself. Anyway, it isn't recommending that you use relative paths in general. Instead, you should use absolute paths by default, and you should use relative paths only if you have a good reason. If you look at PEP8 in my link above it'll give you more explanation about this. – Justin Payan Nov 14 '17 at 00:28