Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parameter type-setting returning SyntaxError

I have a python script that contains a type declaration of function arguments as following:

def dump_var(v: Variable, name: str = None):

To my knowledge, this is a valid syntax that sets a type of input parameters to the function, but it returns a

SyntaxError: invalid syntax

What may be wrong?

like image 979
ytrewq Avatar asked Oct 19 '25 12:10

ytrewq


1 Answers

The SyntaxError is because Python 2.7 doesn't support type hints. You may either use Python 3.5+ or use type hints for Python 2.7 in comments as PEP 484 suggests:

Suggested syntax for Python 2.7 and straddling code

Some tools may want to support type annotations in code that must be compatible with Python 2.7. For this purpose this PEP has a suggested (but not mandatory) extension where function annotations are placed in a # type: comment. Such a comment must be placed immediately following the function header (before the docstring). An example: the following Python 3 code:

def embezzle(self, account: str, funds: int = 1000000, *fake_receipts: str) -> None:
    """Embezzle funds from account using fake receipts."""
    <code goes here>

is equivalent to the following:

def embezzle(self, account, funds=1000000, *fake_receipts):
    # type: (str, int, *str) -> None
    """Embezzle funds from account using fake receipts."""
    <code goes here>
like image 111
Sarath Sadasivan Pillai Avatar answered Oct 22 '25 02:10

Sarath Sadasivan Pillai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!