josh
josh

Reputation: 59

Python Nesting Modules

I have spent a lot of time researching this and still cannot understand why I keep getting ImportErrors: No module named ...

My file structure is as follows:

/Package
    /mode
        __init__.py
        moduletoimport.py
        /test
            __init__.py
            abc.py

File moduletoimport.py contains:

class ClassToImport(object):
    def test(self):
        return True

File abc.py contains the following code:

from mode.moduletoimport import ClassToImport

From the terminal I type:

python abc.py

The aim here is to import a module that is up the directory.

Upvotes: 1

Views: 1171

Answers (1)

loganasherjones
loganasherjones

Reputation: 1062

Quick Fix

A quick fix to this problem is, in the file abc.py add the following to the top of the file:

import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))

However, this is really not that correct. I have some serious questions about the way you're structuring your project and believe the below section will help greatly.

Better Solution

In general, if you're designing a module to be imported, you want your project structure to look something like this:

package_name/
  /* setup.py and other misc files */
  package_name/
    __init__.py
    /* module files go here */
  test/
    /* tests go here */

The top level package_name/ is really just for holding the project. It will contain your setup.py, possibly configuration things etc.

Underneath the top level, we have another directory called package_name. This is where all your actual python code will go.

Also underneath the top level, we have another directory called test. This is where all the tests should go. I would strongly consider using nose to test your python application.

Example

Let's build a quick example of what you are trying to accomplish. The final product will have the following structure/files:

my_project/
  my_project/
    __init__.py
    my_class.py
  test/
    test_my_class.py

The contents of my_class.py are:

class MyClass(object):

  def test(self):
    return True

The contents of test_my_class.py are:

import unittest
from my_project.my_class import MyClass

class TestMyClass(unittest.TestCase):

  def test_my_class(self):
    c = MyClass()
    self.assertEqual(c.test(), True)

Now, if you install nose you should be able to (from the top level of your project) run nosetests.

There are tons of tutorials out there for how to do this. But for brevity's sake, I'll let you do some searching on your own.

Hope this helps.

Upvotes: 1

Related Questions