嵌套python,Python嵌套模块

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值