【问题标题】:Import error trying to import a module that has class methods with typed parameters尝试导入具有带类型参数的类方法的模块时出现导入错误
【发布时间】:2018-02-22 00:22:49
【问题描述】:

我正在尝试导入我创建的模块 (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 python-import importerror


    【解决方案1】:

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

    很可能(给定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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-27
      • 2019-07-01
      • 2012-10-14
      • 2019-10-27
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多