尝试导入具有带类型参数的 class 方法的模块时出现导入错误

Import error trying to import a module that has class methods with typed parameters

我正在尝试导入我创建的模块 (module_name.py) using __import__() 但我看到以下错误:

Traceback (most recent call last):
  File "test.py", line 80, in <module>
    testImportMethod()
  File "test.py", line 68, in testImportMethod
    m = __import__("module_name")
  File "/dir/module_name.py", line 147
    def insert_model(model: MyModel):
                          ^  
SyntaxError: invalid syntax

module_name.py 具有以下代码:

class MyModel(object):
    property1 = None
    property2 = None

class ThingDAO(object):
    @staticmethod
    def get_thing_by_id(id):
    ...

    @staticmethod
    def insert_model(model: MyModel):
    ...

为什么导入过程中输入的参数有问题?

类型化参数有问题的不是导入过程。问题是在 Python 3.5 (PEP 484) 中添加了类型化参数,并在 Python 2.7.

中引发此类语法错误

可能(给定 SyntaxError)您使用的是 Python 的旧版本,要使其正常工作,您要么必须安装并使用更新的 Python 版本,要么使用workarounds mentioned in the PEP 中的一个,例如:

class MyModel(object):
    property1 = None
    property2 = None

class ThingDAO(object):
    @staticmethod
    def get_thing_by_id(id):
        pass

    @staticmethod
    def insert_model(model):
        # type: (MyModel) -> None
        pass