Python Latest Features and Tips
Note that Python 3.5 was released on Sep 2015.
Coroutines with Async/Await Syntax:
Matrix Multiplication Operator (@
):
Unpacking Generalization:
*
operator for unpacking in function calls and tuples
Type Hints:
F-Strings:
Breakpoint() Function:
Assignment Expressions (:=
):
__annotations__
attribute of functions and classesfrom typing import get_type_hints
def greeting(name: str) -> str:
return 'Hello ' + name
type_hints = get_type_hints(greeting)
print(type_hints) # Output: {'name': <class 'str'>, 'return': <class 'str'>}
Its popularity has been significantly boosted by its integration with frameworks like FastAPI
Data Validation: Automatically checks types and values against specified constraints.
Complex Data Types: Supports lists, dictionaries, and nested models.
Efficiency: Fast and lightweight with minimal dependencies.
Custom Validators: Allows for custom validation rules using Python type hinting.
JSON Schema Generation: Can generate JSON schemas for data models
Pydantic is the most widely used data validation library for Python, with over 70 million downloads per month.
It is used by FastAPI, huggingface, and Django Ninja, etc
Example of Runtime Validation:
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
try:
user = User(id='123', name='John Doe')
print(user.id) # Success. Output: 123 (validated and converted to int)`
user = User(name='John', age='twenty') # Raises ValidationError here
except ValidationError as e:
print(f"Validation error: {e}") # Optionally log a warning or handle the error as needed`
FastAPI Custom Error Handling:
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
app = FastAPI() @app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
error_messages = []
for error in exc.errors():
error_messages.append({ "location": error["loc"], "message": error["msg"], "type": error["type"], })
return JSONResponse(status_code=422, content={"errors": error_messages})
This custom handler formats the error response to include detailed information about validation failures.
See https://github.com/EvanLi/Github-Ranking/blob/master/Top100/Python.md
uvicorn - A lightning-fast ASGI server implementation, using uvloop and httptools.
starlette is a core ASGI framework used by FastAPI. uvicorn is a ASGI server running FastAPI applications.
Python built-in dataclass annotation to reduce boiler plate: https://docs.python.org/3/library/dataclasses.html
Improved version of python dataclasses: attrs