Python Nesting Modules
Solution 1:
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:
classMyClass(object):
deftest(self):
returnTrueThe contents of test_my_class.py are:
import unittest
from my_project.my_classimport MyClass
classTestMyClass(unittest.TestCase):
deftest_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.
Post a Comment for "Python Nesting Modules"