2

I have the following file structure:

├───common
│       hdfs.py
│       impala.py
│       pandasUtils.py
│       proxy.py
│       stringUtils.py
│       __init__.py
│
├───tests
│   └───unitTests
│           test_stringUtils.py
│           __init__.py

From tests/unitTests/test_stringUtils.py, I want to import the file common/stringUtils.py

I tried the following:

import unittest
from common.stringUtils import StringUtils

But I have the following error: Unable to import 'common.stringUtils'.

Is there a way to import a file without dealing with sys path or doing anything different from "import from" ?(30 years and still looks like an early access game)

Itération 122442
  • 2,644
  • 2
  • 27
  • 73

1 Answers1

2

Use PYTHONPATH. For example

PYTHONPATH=. python tests/unitTests/test_stringUtils.py

or

PYTHONPATH=.. python unitTests/test_stringUtils.py
ghchoi
  • 4,812
  • 4
  • 30
  • 53
  • More generally, `common` is a package you want to use from the test script. Ensure that the directly *containing* `common` is on your Python path. – chepner Feb 24 '21 at 16:07
  • With frim common.stringUtils, this works fine. But isn't there a way to NOT have to say "hey use this path" ? – Itération 122442 Feb 25 '21 at 09:21
  • @FlorianCastelain Well, you can put it into the Python package folder which is already in `PYTHONPATH` technically. Or, you should use `sys.path`. Either way, you should tell Python where files are. – ghchoi Feb 25 '21 at 10:07