python 2 语法错误当 运行 python 3 代码

python 2 syntax error when running python 3 code

我有一个 class 如下所示

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__)

代码写在 python 3 中,而我试图 运行 它写在 python 2 中。 当我 运行 我得到

    def __init__(self, result_type: str, data: dict, references: list):
                                  ^
SyntaxError: invalid syntax

有"import_from_future"解决这个问题吗?

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

语法细节见Suggested syntax for Python 2.7 and straddling code section of PEP 484 and the Type checking Python 2 code section

For code that needs to be Python 2.7 compatible, function type annotations are given in comments, since the function annotation syntax was introduced in 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