-2

I was wondering if notations mattered in Python.

These are both the same functions, same input and output:

# example 1
def add(x, y):
    return x + y
# example 2
def add(x: int, y: int) -> int:
    return x + y

Does example 2 makes your code faster?

3
  • 1
    No, it does not make the code faster. When python runs your code, it completely ignores type annotations. The actual type analysis is done by a completely separate program. Commented Feb 14 at 18:32
  • Voting to reopen because "run time effects" will normally make one think of enforcement, which differs from performance - and then, there are whole tool echo-system which can be presented and expanded in answers to this question. Commented Feb 20 at 22:01
  • 2
    Some Python compilers make use of type annotations to compile Python or Python-like code into native code, so the answer is "yes" if you use such a compiler. On the top of my head, these are the ones that are active: mypyc, Cython (especially its pure Python mode), CinderX, SPy. mojo. Commented Feb 20 at 22:22

2 Answers 2

1

"It depends": if you're asking about whether it runs faster using the Python Foundation's interpreter, then no, they get completely ignored at runtime, and are meant for use with linting tools like mypy or ruff, so that you can make sure your code won't run into type incompatibility issues at runtime.

But the Python interpreter is not the only way to execute code written in Python, the programming language. Numerous Python compilers exist, which do look at type annotations and use that to generate optimized machine code so that the code does run faster.

The "big two" here are Mypyc and Cython, but there's a host of lesser-known Python compilers that all take advantage of type annotations.

Sign up to request clarification or add additional context in comments.

2 Comments

Nit: I don't believe there are compilers which use annotations to generate optimised bytecode; the compilers that I'm aware of all generate Python extension modules which are compiled and executed as native machine code. The speedups in newer versions of CPython actually do optimise bytecode, but they still don't look at type annotations at all (and neither does the JIT introduced in Python 3.13).
That's actually a really good point, I was playing fast and loose with terms myself here: I definitely meant machine code, and should not have used the term "byte code". I've updated the answer.
-2

In Python 3.14, the Python interpreter does not use type annotations to optimize generated bytecode, so no.

It might change in the future, but as far as I'm aware, there are no concrete plans for this yet.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.