Type annotations in pypy give an error but work in python3

82 views Asked by At

Please compare the following two programs:

#!/usr/bin/env pypy

i: float = 5.0

and this:

#!/usr/bin/env python3

i: float = 5.0

The first one fails:

  File "./pypy_test.py", line 3
    i: float = 5.0
     ^
SyntaxError: invalid syntax

The second one just runs. I thought pypy and Python were fully compatible. What could be going on?

The installation of pypy on my Ubuntu is just a few minutes old. I am running Python 3.10.12.

2023_11_25 14:57:08 maot@hunsn:~  $ pypy --version
Python 2.7.18 (7.3.9+dfsg-1, Apr 01 2022, 21:40:34)
[PyPy 7.3.9 with GCC 11.2.0]
2023_11_25 14:57:11 maot@hunsn:~  $ 
1

There are 1 answers

0
mkrieger1 On BEST ANSWER

As you can see from the output of pypy --version, that is a PyPy version which implements the Python 2 language.

Type annotations (i: float syntax) only exist in the Python 3 language. In particular, variable annotations were introduced in Python 3.6 by PEP 526.

You need to use a PyPy version which implements Python 3. Packages and binaries are typically named pypy3, not pypy.

e.g. on Ubuntu: https://packages.ubuntu.com/mantic/pypy3

File list:

/usr/bin/pypy3
[...]