2017-08-16 63 views
0

时,我有一个类,它看起来像下面蟒蛇2语法错误运行的Python 3代码

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 2 当我运行的代码是用Python编写3它我得到

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

有没有“import_from_future”来解决这个问题?

+2

真正溶胶ution是*停止运行** Python 2中的所有**代码* –

回答

7

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

见PEP 484的Suggested syntax for Python 2.7 and straddling code部分和Type checking Python 2 code section的语法细节:

对于需要在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