Python Latest Features and Tips

Significant Features Introduced in Python 3.5 or Later

Note that Python 3.5 was released on Sep 2015.

Coroutines with Async/Await Syntax:

  • This feature allows developers to write asynchronous code that appears sequential
  • It was a major addition.

Matrix Multiplication Operator (@):

  • Introduced to simplify matrix multiplication operations.

Unpacking Generalization:

  • Extended the use of the * operator for unpacking in function calls and tuples

Type Hints:

  • Introduced in Python 3.5; Major Feature.
  • Variables can be annotated with types
  • No runtime checking.

F-Strings:

  • Introduced in Python 3.6, f-strings provide a more readable way to format strings,
  • Further enhanced in Python 3.8 with debugging capabilities5.

Breakpoint() Function:

  • Introduced in Python 3.7, this function enables debugging at specific points.

Assignment Expressions (:=):

  • Introduced in Python 3.8, this allows assigning values within expressions for brevity.

Pydantic : Data Validation Library

  • Pydantic is a powerful Python library for data validation and parsing, created by Samuel Colvin.
  • It is mainly useful during runtime and makes use of Python type hints (which is usually only used by linters)
  • Python type hints are available at runtime, but they are not enforced
  • Type hints are stored as metadata in the __annotations__ attribute of functions and classes
from 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.