32
loading...
This website collects cookies to deliver better user experience
PEP stands for Python Enhancement Proposals, all proposals and specifications of Python's features. It's like ECMA's documents for Javascript.
AttributeError: 'X' object has no attribute 'Y'
Big Security Guy: "Let's say you have a choice between 2 options.
(1) Passing a security check which includes long lines and cursings.
(2) you go freely into your airplane and during the flight, you'll be checked.
What would you prefer?"
e.g: Java, C, C++
e.g: Python, Javascript, R, Julia
int, str, float, bool, bytes, object, None
.Notice that in Python3.9+ most of the following types are changed and won't be imported anymore from typing
module anymore, e.g, List -> list.
Any
Any type is possible.List[str]
List of str objects.Tuple[int, int]
Tuple of two ints.Tuple[int, ...]
Tuple of int objects.Dict[int, int]
Dict with int keys to int values.Iterable[int]
Iterable which contains int objects.Sequence[bool]
Sequence of booleans.By the way: Sequence is an Iterable with defined length and extra functionality.
def greeting(name: str) -> str:
return 'Hello ' + name
greeting(3)
we will get the following error:error: Argument 1 to "greeting" has incompatible type "int"; expected "str"
Url = str
def retry(url: Url, retry_count: int) -> None:
pass
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
# Create an empty list with items of type T
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
def empty(self) -> bool:
return not self.items
# Construct an empty Stack[int] instance
stack = Stack[int]()
stack.push(2)
stack.pop()
stack.push('x') # Type error
Union[T1,...,Tn]
def f(x: Union[int, str]) -> None:
if isinstance(x, int):
x + 1 # OK
else:
x + 'a' # OK
f(1) # OK
f('x') # OK
f(1.1) # Error
Optional[T]
None
.Union[T, None]
.def strlen(s: str) -> Optional[int]:
if not s:
return None # OK
return len(s)
int
variable and string
suggestions are made. __annotations__
property.def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9):
...
> foo.__annotations__
{'a': 'x',
'b': 11,
'c': list,
'return': 9}
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
# main.py
def print_hi(name: str) -> None:
print(f'Hi, {name}')
> mypy main.py
> main.py:4: error: Argument 1 to "print_hi" has incompatible type "int"; expected "str"
MonkeyType
and PyAnnotate
tools can infer the types of your code during runtime.# type: ignore
and move on. Subset by subset, Part by part.
There is a big advantage having a big codebase with Type Annotations, refactoring will be easier and bugs can be detected fast.Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.