Search code examples
pythonpython-2.7python-typing

python 2 syntax error when running python 3 code


I have a class that looks like the following

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

The code is written in python 3 while I am trying to run it in python 2. When I run it I get

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

Is there an "import_from_future" to solve this?


Solution

  • No, there is no __future__ switch that'll enable Python 3 annotations in Python 2. If you are using annotations for type hinting, use comments instead.

    See the Suggested syntax for Python 2.7 and straddling code section of PEP 484 and the Type checking Python 2 code section for the syntax details:

    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.

    For your specific example, that'd be:

    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