slipperypete
slipperypete

Reputation: 6246

How to import a class from another file in python?

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?

Upvotes: 7

Views: 24645

Answers (1)

Nikolas Stevenson-Molnar
Nikolas Stevenson-Molnar

Reputation: 4700

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

Upvotes: 9

Related Questions