Python
Type Annotations
27 flashcards · answers and spaced-repetition review in the KnowCard app
What does this print, and does it raise?
```
def repeat(s: str, n: int) -> str:
return s * n
print(repeat(["P"], 3))
```
True or false: adding type annotations makes Python check the argument types when a function is called, raising an error on a mismatch.
What is the correct syntax to annotate a function's parameters AND its return type?
Does Optional[int] mean the argument is optional (can be omitted)?
What is Optional[X] equivalent to, written as a plain union?
How do you annotate a variable (with and without assigning a value)?
What does this print?
```
from typing import get_type_hints
def f(x: int) -> str:
return str(x)
print(get_type_hints(f))
```
Where does the Python interpreter store an object's annotations, and what's the recommended way to read them?
Which annotations can be retrieved at runtime via get_type_hints, and which cannot?
Since Python 3.9, how do you annotate a list of ints or a dict of str→int without importing from typing?
What's the difference between tuple[int, str] and tuple[int, ...] as type hints?
Why does this raise NameError, and how do you fix it?
```
class Test:
def __add__(self, other: Test):
...
```
What does from __future__ import annotations change about how annotations behave?
Since Python 3.10, what's the modern way to write Union[int, float] and Optional[str]?
In a type hint, what does Any mean — and what is the implicit type of an unannotated parameter?
How do you annotate a one-arg callable taking an int and returning a str?
What does a TypeVar express that you can't get from Any, in a signature like def f(p: list[T]) -> T?
What does this print?
```
def f():
x: blahblah = 12
return x
print(f())
```
What is a type alias, and how do you create one?
Who actually catches a type error in annotated code, and when?
You want to annotate a loop variable: for i: int in range(3):. Why is that a syntax error, and what's the workaround?
A function should accept any iterable of ints, not specifically a list[int]. What's the recommended way to annotate that?
In T = TypeVar("T"), what does the string "T" do, and how do you restrict a type variable to only str or bytes?
Which of these two lines raises NameError when the class is defined? (nope is undefined)
class C:
attr: nope = 1 # A
def __init__(self):
self.x: nope = 2 # B
If Python is dynamically typed and relies on duck typing, why were type hints added at all?
Before the x: type annotation syntax existed, how were type hints written so they'd be ignored at runtime but still readable by tools?
What are the annotated data types in a signature collectively called, and which Python version first introduced the def f(x: int) -> str annotation syntax?
Start learning today
Free to start — download the app or use it in your browser.
