8

Im new to python and have looked at various stack overflow posts. i feel like this should work but it doesnt. How do you import a class from another file in python? This folder structure

src/example/ClassExample
src/test/ClassExampleTest

I have this class

class ClassExample:
    def __init__(self):
        pass

    def helloWorld(self):
        return "Hello World!"

I have this test class

import unittest
from example import ClassExample

class ClassExampleTest(unittest.TestCase):

    def test_HelloWorld(self):
        hello = ClassExample()
        self.assertEqual("Hello World!", hello.helloWorld())

if __name__ == '__main__':
    unittest.main()

When the unit test runs the object is None:

AttributeError: 'NoneType' object has no attribute 'helloWorld'

What's wrong with this? How do you import a class in python?

10
  • 1
    Try import example; print(example) to see you actually imported the example module, not other module that is in python import path. Commented Nov 25, 2020 at 4:31
  • I don't see how hello can be None. Commented Nov 25, 2020 at 4:32
  • The code shown here looks reasonable. Make sure you are importing from the correct file. Change file names to verify you are not reading from the wrong file. Commented Nov 25, 2020 at 4:33
  • when I do what @falsetru says it prints "<module 'example' from '/Users/thomas/.pyenv/versions/3.6.1/lib/python3.6/site-packages/example/__init__.py'>" Commented Nov 25, 2020 at 4:33
  • It sounds like the site-package example module actually has a "ClassExample" class. What are the odds?? Commented Nov 25, 2020 at 4:35

1 Answer 1

9

If you're using Python 3, then imports are absolute by default. This means that import example will look for an absolute package named example, somewhere in the module search path.

So instead, you probably want a relative import. This is useful when you want to import a module that is relative the module doing the importing. In this case:

from ..example.ClassExample import ClassExample

I'm assuming that your folders are Python packages, meaning that they contain __init__.py files. So your directory structure would look like this.

src
|-- __init__.py
|-- example
|   |-- __init__.py
|   |-- ClassExample.py
|-- test
|   |-- __init__.py
|   |-- ClassExampleTest.py
Sign up to request clarification or add additional context in comments.

12 Comments

I tried this. I get: TypeError: 'module' object is not callable
Ah. Do you have your class inside a file named ClassExample.py?
Relative import doesn't work for scripts (like this unit test script), only for packages and modules. Scripts aren't in packages so there is nothing to be relative to.
Yes. That is it Nikolas
@Dan, in that case, you need from .example.ClassExample import ClassExample
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.