Python Decorators Guide The Power of Python Decorators At their core, Python’s decorators allow you to extend and modify the behavior of a callable (functions, methods, and classes) without permanently modifying the callable itself. Any sufficiently generic functionality you can tack on to an existing class or function’s behavior makes a great use case for decoration. This includes the following: logging enforcing access control and authentication instrumentation and timing functions rate-limiting caching and more Sure, decorators are relatively complicated to wrap your head around for the first time, but they’re a highly useful feature that you’ll often encounter in third-party frameworks and the Python standard library. Python Development
Fabulous Python Decorators @cache @functools.cache(user_function) Simple lightweight unbounded function cache. Sometimes called "memoize" . Returns the same as lru_cache(maxsize=None), creating a thin wrapper around a dictionary lookup for the function arguments. Because it never needs to evict (remove) old values, this is smaller and faster than lru_cache() with a size limit. example: from functools import cache @cache def factorial(n): return n * factorial(n-1) if n else 1 >>> factorial(10) # no previously cached result, makes 11 recursive calls 3628800 >>> factorial. Python Development
Python Decorators Cheat Sheet Using decorators The normal way of using a decorator is by specifying it just before the definition of the function you want to decorate: @decorator def f(arg_1, arg_2): ... If you want to decorate an already existing function you can use the following syntax: f = decorator(f) Decorator not changing the decorated function If you don’t want to change the decorated function, a decorator is simply a function taking in and returning a function: Python Development
Complex Request Validation in FastAPI with Pydantic Why should you care? 🤔 Pydantic + FastAPI gets along very well, and provide easy to code, type-annotation based basic validations for atomic types and complex types (created from atomic types). What happens when these basic validations aren’t sufficient for you and you would like to do much more complex? 😲 We use @validator decorator in Pydantic to perform complex validation per request parameter. Let’s dive in.. 🤿 Here’s how we’ll go about this, we are gonna construct a simple API endpoint for printing the date given the day number of the present year. Python Development
Python - How traverse filesystem directory Every so often you will find yourself needing to write code that traverse a directory. They tend to be one-off scripts or clean up scripts that run in cron in my experience. Anyway, Python provides a very useful methods of walking a directory structure. We cover best of them. Testing directory structure Here is my testing filesystem tree. Root is in /test ~] tree -a /test /test ├── A │ ├── AA │ │ └── aa. Python Development
Python Map, Filter and Reduce functions Python Map, Filter and Reduce are three functions which facilitate a functional approach to programming. We will discuss them one by one and understand their use cases. Python Development
Python filter and filterfalse functions guide Let's learn about the differences between filter() and itertools.filterfalse() in python. Python Development
Python map and starmap functions python map function python map function map(function, iterable, ...) Python map function Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools. Python Development
Python reduce and accumulate total guide Python reduce function Python’s reduce() implements a mathematical technique commonly known as folding or reduction. You’re doing a fold or reduction when you reduce a list of items to a single cumulative value. Python’s reduce() operates on any iterable (not just lists) and performs the following steps: Apply a function (or callable) to the first two items (default) in an iterable and generate a partial result. Use that partial result, together with the third item in the iterable, to generate another partial result. Python Development
Python case|match - structural pattern matching After many proposals to add a switch/case like syntax to Python failed, a recent proposal by Python language creator Guido van Rossum and a number of other contributors has been accepted for Python 3.10: structural pattern matching . Structural pattern matching not only makes it possible to perform simple switch/case style matches, but also supports a broader range of use cases. Python structural pattern matching Structural pattern matching introduces the match/case statement and the pattern syntax to Python. Python Development
Python Multiprocessing - Right Way We will not write about what multiprocessing is. You can find many articles about what is multiprocessing . Although cumbersome at first sight, multiprocessing does have several advantages. Keeping processes separated in their own virtual memory "cages" can actually help in debugging and avoids confusion. Once you sort out the intercommunication problem in a systematic way and avoid some common pitfalls, programming with python multiprocesses becomes a joy. One frequent error is to mix multithreading and multiprocessing together, creating a crashy/leaky program and then conclude that python sucks. Python Development
FastAPI language translations I18n Step by Step Since the beginning of 2020, FastAPI has been gaining momentum as one of the potential alternatives to Flask server for RESTful API. If you are an existing FastAPI user, you should be aware that it does not come with built-in internationalization, and that will likely not change soon, because internationalization strategies are application-dependent. The following tutorial focuses on server-side i18n . This tutorial will show you how to i18n your FastAPI web application easily using the following Python libraries: Python Development