运行python 3代码时出现python 2语法错误

gab*_*how 0 python annotations type-hinting python-2.7 python-3.x

我有一个如下所示的课程

class ExperimentResult(BaseDataObject):
    def __init__(self, result_type: str, data: dict, references: list):
        super().__init__()
        self.type = result_type
        self.references = references
        self.data = data

    def __repr__(self):
        return str(self.__dict__)
Run Code Online (Sandbox Code Playgroud)

代码是用python 3编写的,而我正在尝试在python 2中运行它.当我运行它时,我得到了

    def __init__(self, result_type: str, data: dict, references: list):
                                  ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

是否有"import_from_future"来解决这个问题?

Mar*_*ers 7

不,没有__future__可以在Python 2中启用Python 3注释的开关.如果您使用注释进行类型提示,请改用注释.

有关语法详细信息,请参阅PEP 484的Python 2.7和straddling code部分的Suggested语法Type check Python 2 code部分:

对于需要与Python 2.7兼容的代码,函数类型注释在注释中给出,因为函数注释语法是在Python 3中引入的.

对于您的具体示例,那将是:

class ExperimentResult(BaseDataObject):
    def __init__(self, result_type, data, references):
        # type: (str, dict, list) -> None
        super().__init__()
        self.type = result_type
        self.references = references
        self.data = data
Run Code Online (Sandbox Code Playgroud)