首页 > 解决方案 > 如何构建包以使其模块可调用?

问题描述

我对 Python 很陌生,正在学习包和模块的工作原理,但遇到了障碍。最初,我创建了一个非常简单的包来部署为 Lambda 函数。我在根目录中有一个名为的文件,lambda.py其中包含一个handler函数,并且我将大部分业务逻辑放在一个单独的文件中。我创建了一个子目录——对于这个例子,假设它被称为testme——更具体地说,把它放在__init__.py那个子目录下面。最初,这很好用。在我的lambda.py文件中,我可以使用以下import语句:

from testme import TestThing # TestThing is the name of the class

但是,现在代码正在增长,我一直在将内容拆分为多个文件。结果,我的代码不再运行;我收到以下错误:

TypeError: 'module' object is not callable

这是我的代码现在的简化版本,以说明问题。我错过了什么?我该怎么做才能使这些模块“可调用”?

/lambda.py:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from testme import TestThing


def handler(event, context):
    abc = TestThing(event.get('value'))
    abc.show_value()


if __name__ == '__main__':
    handler({'value': 5}, None)

/testme/__init__.py:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
__project__ = "testme"
__version__ = "0.1.0"
__description__ = "Test MCVE"
__url__ = "https://stackoverflow.com"
__author__ = "soapergem"
__all__ = ["TestThing"]

/testme/TestThing.py:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-


class TestThing:

    def __init__(self, value):
        self.value = value

    def show_value(self):
        print 'The value is %s' % self.value

就像我说的那样,我这样做的原因是因为现实世界的示例有足够的代码,我想将它拆分为子目录中的多个文件。所以我在__init__.py那里留下了一个文件,基本上只是作为一个索引。但我非常不确定包结构的最佳实践是什么,或者如何让它发挥作用。

标签: python

解决方案


您要么必须在文件中导入您的课程__init__

testme/__init__.py

from .TestThing import TestThing

或使用完整路径导入:

lambda.py

from testme.TestThing import TestThing

当你使用一个__init__.py文件时,你创建了一个包,这个包(以根目录命名,例如 testme,可能包含子模块。这些可以通过package.module语法访问,但子模块的内容只有在根包中可见,如果你在那里显式导入它们。


推荐阅读