functools — Fonctions d'ordre supérieur et opérations sur des objets appelables

Code source : Lib/functools.py


Le module functools concerne les fonctions d'ordre supérieur : des fonctions qui agissent sur, ou renvoient, d'autres fonctions. En général, tout objet appelable peut être considéré comme une fonction dans la description de ce module.

Le module functools définit les fonctions suivantes :

@functools.cache(user_function)

Fonction de cache très simple et sans limite de taille. Cette technique est parfois appelée « mémoïsation ».

Identique à lru_cache(maxsize=None). Crée une surcouche légère avec une recherche dans un dictionnaire indexé par les arguments de la fonction. Comme elle ne nettoie jamais les anciennes entrées, elle est plus simple et plus rapide que lru_cache() avec une limite.

Par exemple :

@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(5)       # just looks up cached value result
120
>>> factorial(12)      # makes two new recursive calls, the other 10 are cached
479001600

The cache is threadsafe so that the wrapped function can be used in multiple threads. This means that the underlying data structure will remain coherent during concurrent updates.

It is possible for the wrapped function to be called more than once if another thread makes an additional call before the initial call has been completed and cached.

Nouveau dans la version 3.9.

@functools.cached_property(func)

Transform a method of a class into a property whose value is computed once and then cached as a normal attribute for the life of the instance. Similar to property(), with the addition of caching. Useful for expensive computed properties of instances that are otherwise effectively immutable.

Exemple :

class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)

The mechanics of cached_property() are somewhat different from property(). A regular property blocks attribute writes unless a setter is defined. In contrast, a cached_property allows writes.

The cached_property decorator only runs on lookups and only when an attribute of the same name doesn't exist. When it does run, the cached_property writes to the attribute with the same name. Subsequent attribute reads and writes take precedence over the cached_property method and it works like a normal attribute.

The cached value can be cleared by deleting the attribute. This allows the cached_property method to run again.

The cached_property does not prevent a possible race condition in multi-threaded usage. The getter function could run more than once on the same instance, with the latest run setting the cached value. If the cached property is idempotent or otherwise not harmful to run more than once on an instance, this is fine. If synchronization is needed, implement the necessary locking inside the decorated getter function or around the cached property access.

Note, this decorator interferes with the operation of PEP 412 key-sharing dictionaries. This means that instance dictionaries can take more space than usual.

Also, this decorator requires that the __dict__ attribute on each instance be a mutable mapping. This means it will not work with some types, such as metaclasses (since the __dict__ attributes on type instances are read-only proxies for the class namespace), and those that specify __slots__ without including __dict__ as one of the defined slots (as such classes don't provide a __dict__ attribute at all).

If a mutable mapping is not available or if space-efficient key sharing is desired, an effect similar to cached_property() can also be achieved by stacking property() on top of lru_cache(). See Comment mettre en cache le résultat d'une méthode ? for more details on how this differs from cached_property().

Nouveau dans la version 3.8.

Modifié dans la version 3.12: Prior to Python 3.12, cached_property included an undocumented lock to ensure that in multi-threaded usage the getter function was guaranteed to run only once per instance. However, the lock was per-property, not per-instance, which could result in unacceptably high lock contention. In Python 3.12+ this locking is removed.

functools.cmp_to_key(func)

Transforme une fonction de comparaison à l'ancienne en une fonction clé. Utilisé avec des outils qui acceptent des fonctions clef (comme sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby()). Cette fonction est destinée au portage de fonctions python 2 utilisant des fonctions de comparaison vers Python 3.

A comparison function is any callable that accepts two arguments, compares them, and returns a negative number for less-than, zero for equality, or a positive number for greater-than. A key function is a callable that accepts one argument and returns another value to be used as the sort key.

Exemple :

sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order

Pour des exemples de tris et un bref tutoriel, consultez Sorting Techniques.

Nouveau dans la version 3.2.

@functools.lru_cache(user_function)
@functools.lru_cache(maxsize=128, typed=False)

Décorateur qui englobe une fonction avec un appelable mémoïsant qui enregistre jusqu'à maxsize appels récents. Cela peut gagner du temps quand une fonction coûteuse en ressources est souvent appelée avec les mêmes arguments.

The cache is threadsafe so that the wrapped function can be used in multiple threads. This means that the underlying data structure will remain coherent during concurrent updates.

It is possible for the wrapped function to be called more than once if another thread makes an additional call before the initial call has been completed and cached.

Since a dictionary is used to cache results, the positional and keyword arguments to the function must be hashable.

Distinct argument patterns may be considered to be distinct calls with separate cache entries. For example, f(a=1, b=2) and f(b=2, a=1) differ in their keyword argument order and may have two separate cache entries.

Si user_function est défini, ce doit être un appelable. Ceci permet à lru_cache d'être appliqué directement sur une fonction de l'utilisateur, sans préciser maxsize (qui est alors défini à sa valeur par défaut, 128) :

@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')

Si maxsize est à None, la fonctionnalité LRU est désactivée et le cache peut grossir sans limite.

If typed is set to true, function arguments of different types will be cached separately. If typed is false, the implementation will usually regard them as equivalent calls and only cache a single result. (Some types such as str and int may be cached separately even when typed is false.)

Note, type specificity applies only to the function's immediate arguments rather than their contents. The scalar arguments, Decimal(42) and Fraction(42) are be treated as distinct calls with distinct results. In contrast, the tuple arguments ('answer', Decimal(42)) and ('answer', Fraction(42)) are treated as equivalent.

The wrapped function is instrumented with a cache_parameters() function that returns a new dict showing the values for maxsize and typed. This is for information purposes only. Mutating the values has no effect.

To help measure the effectiveness of the cache and tune the maxsize parameter, the wrapped function is instrumented with a cache_info() function that returns a named tuple showing hits, misses, maxsize and currsize.

Le décorateur fournit également une fonction cache_clear() pour vider ou invalider le cache.

La fonction sous-jacente originale est accessible à travers l'attribut __wrapped__. Ceci est utile pour l'introspection, pour outrepasser le cache, ou pour ré-englober la fonction avec un cache différent.

The cache keeps references to the arguments and return values until they age out of the cache or until the cache is cleared.

If a method is cached, the self instance argument is included in the cache. See Comment mettre en cache le résultat d'une méthode ?

Un cache LRU (*least recently used*) fonctionne de manière optimale lorsque les appels récents sont les prochains appels les plus probables (par exemple, les articles les plus lus d'un serveur d'actualités ont tendance à ne changer que d'un jour à l'autre). La taille limite du cache permet de s'assurer que le cache ne grossisse pas sans limite dans les processus à longue durée de vie comme les serveurs Web.

In general, the LRU cache should only be used when you want to reuse previously computed values. Accordingly, it doesn't make sense to cache functions with side-effects, functions that need to create distinct mutable objects on each call (such as generators and async functions), or impure functions such as time() or random().

Exemple d'un cache LRU pour du contenu web statique :

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = f'https://peps.python.org/pep-{num:04d}'
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)

Exemple de calcul efficace de la suite de Fibonacci en utilisant un cache pour implémenter la technique de programmation dynamique :

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)

Nouveau dans la version 3.2.

Modifié dans la version 3.3: L'option typed a été ajoutée.

Modifié dans la version 3.8: Ajout de l'option user_function.

Modifié dans la version 3.9: Added the function cache_parameters()

@functools.total_ordering

A partir d'une classe définissant une ou plusieurs méthodes de comparaison riches, ce décorateur de classe fournit le reste. Ceci simplifie l'effort à fournir dans la spécification de toutes les opérations de comparaison riche :

La classe doit définir au moins une de ces méthodes __lt__(), __le__(), __gt__(), ou __ge__(). De plus, la classe doit fournir une méthode __eq__().

Par exemple :

@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))

Note

Même si ce décorateur permet de créer des types ordonnables facilement, cela vient avec un coût d'exécution et des traces d'exécution complexes pour les méthodes de comparaison dérivées. Si des tests de performances le révèlent comme un goulot d'étranglement, l'implémentation manuelle des six méthodes de comparaison riches résoudra normalement vos problèmes de rapidité.

Note

This decorator makes no attempt to override methods that have been declared in the class or its superclasses. Meaning that if a superclass defines a comparison operator, total_ordering will not implement it again, even if the original method is abstract.

Nouveau dans la version 3.2.

Modifié dans la version 3.4: Retourner NotImplemented dans les fonction de comparaison sous-jacentes pour les types non reconnus est maintenant supporté.

functools.partial(func, /, *args, **keywords)

Retourne un nouvel objet partiel qui, quand il est appelé, fonctionne comme func appelée avec les arguments positionnels args et les arguments nommés keywords. Si plus d'arguments sont fournis à l'appel, ils sont ajoutés à args. Si plus d'arguments nommés sont fournis, ils étendent et surchargent keywords. À peu près équivalent à :

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

partial() est utilisé pour une application de fonction partielle qui "gèle" une portion des arguments et/ou mots-clés d'une fonction donnant un nouvel objet avec une signature simplifiée. Par exemple, partial() peut être utilisé pour créer un appelable qui se comporte comme la fonction int() ou l'argument base est deux par défaut :

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
class functools.partialmethod(func, /, *args, **keywords)

Retourne un nouveau descripteur partialmethod qui se comporte comme partial sauf qu'il est fait pour être utilisé comme une définition de méthode plutôt que d'être appelé directement.

func doit être un descriptor ou un appelable (les objets qui sont les deux, comme les fonction normales, sont gérés comme des descripteurs).

Quand func est un descripteur (comme une fonction Python normale, classmethod(), staticmethod(), abstractmethod() ou une autre instance de partialmethod), les appels à __get__ sont délégués au descripteur sous-jacent, et un objet partiel approprié est renvoyé comme résultat.

Quand func est un appelable non-descripteur, une méthode liée appropriée est crée dynamiquement. Elle se comporte comme une fonction Python normale quand elle est utilisée comme méthode : l'argument self sera inséré comme premier argument positionnel, avant les args et keywords fournis au constructeur partialmethod.

Exemple :

>>> class Cell:
...     def __init__(self):
...         self._alive = False
...     @property
...     def alive(self):
...         return self._alive
...     def set_state(self, state):
...         self._alive = bool(state)
...     set_alive = partialmethod(set_state, True)
...     set_dead = partialmethod(set_state, False)
...
>>> c = Cell()
>>> c.alive
False
>>> c.set_alive()
>>> c.alive
True

Nouveau dans la version 3.4.

functools.reduce(function, iterable, [initial, ]/)

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initial is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initial is not given and iterable contains only one item, the first item is returned.

À peu près équivalent à :

initial_missing = object()

def reduce(function, iterable, initial=initial_missing, /):
    it = iter(iterable)
    if initial is initial_missing:
        value = next(it)
    else:
        value = initial
    for element in it:
        value = function(value, element)
    return value

Voir itertools.accumulate() pour un itérateur qui génère toutes les valeurs intermédiaires.

@functools.singledispatch

Transforme une fonction en une fonction générique single-dispatch.

To define a generic function, decorate it with the @singledispatch decorator. When defining a function using @singledispatch, note that the dispatch happens on the type of the first argument:

>>> from functools import singledispatch
>>> @singledispatch
... def fun(arg, verbose=False):
...     if verbose:
...         print("Let me just say,", end=" ")
...     print(arg)

To add overloaded implementations to the function, use the register() attribute of the generic function, which can be used as a decorator. For functions annotated with types, the decorator will infer the type of the first argument automatically:

>>> @fun.register
... def _(arg: int, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> @fun.register
... def _(arg: list, verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)

types.UnionType and typing.Union can also be used:

>>> @fun.register
... def _(arg: int | float, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> from typing import Union
>>> @fun.register
... def _(arg: Union[list, set], verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)
...

Pour le code qui n’utilise pas les indications de type, le type souhaité peut être passé explicitement en argument au décorateur :

>>> @fun.register(complex)
... def _(arg, verbose=False):
...     if verbose:
...         print("Better than complicated.", end=" ")
...     print(arg.real, arg.imag)
...

To enable registering lambdas and pre-existing functions, the register() attribute can also be used in a functional form:

>>> def nothing(arg, verbose=False):
...     print("Nothing.")
...
>>> fun.register(type(None), nothing)

The register() attribute returns the undecorated function. This enables decorator stacking, pickling, and the creation of unit tests for each variant independently:

>>> @fun.register(float)
... @fun.register(Decimal)
... def fun_num(arg, verbose=False):
...     if verbose:
...         print("Half of your number:", end=" ")
...     print(arg / 2)
...
>>> fun_num is fun
False

Quand elle est appelée, la fonction générique distribue sur le type du premier argument :

>>> fun("Hello, world.")
Hello, world.
>>> fun("test.", verbose=True)
Let me just say, test.
>>> fun(42, verbose=True)
Strength in numbers, eh? 42
>>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
Enumerate this:
0 spam
1 spam
2 eggs
3 spam
>>> fun(None)
Nothing.
>>> fun(1.23)
0.615

Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. The original function decorated with @singledispatch is registered for the base object type, which means it is used if no better implementation is found.

If an implementation is registered to an abstract base class, virtual subclasses of the base class will be dispatched to that implementation:

>>> from collections.abc import Mapping
>>> @fun.register
... def _(arg: Mapping, verbose=False):
...     if verbose:
...         print("Keys & Values")
...     for key, value in arg.items():
...         print(key, "=>", value)
...
>>> fun({"a": "b"})
a => b

To check which implementation the generic function will choose for a given type, use the dispatch() attribute:

>>> fun.dispatch(float)
<function fun_num at 0x1035a2840>
>>> fun.dispatch(dict)    # note: default implementation
<function fun at 0x103fe0000>

Pour accéder à toutes les implémentations enregistrées, utiliser l'attribut en lecture seule registry :

>>> fun.registry.keys()
dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
          <class 'decimal.Decimal'>, <class 'list'>,
          <class 'float'>])
>>> fun.registry[float]
<function fun_num at 0x1035a2840>
>>> fun.registry[object]
<function fun at 0x103fe0000>

Nouveau dans la version 3.4.

Modifié dans la version 3.7: The register() attribute now supports using type annotations.

Modifié dans la version 3.11: The register() attribute now supports types.UnionType and typing.Union as type annotations.

class functools.singledispatchmethod(func)

Transforme une méthode en une fonction générique single-dispatch.

To define a generic method, decorate it with the @singledispatchmethod decorator. When defining a function using @singledispatchmethod, note that the dispatch happens on the type of the first non-self or non-cls argument:

class Negator:
    @singledispatchmethod
    def neg(self, arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    def _(self, arg: int):
        return -arg

    @neg.register
    def _(self, arg: bool):
        return not arg

@singledispatchmethod supports nesting with other decorators such as @classmethod. Note that to allow for dispatcher.register, singledispatchmethod must be the outer most decorator. Here is the Negator class with the neg methods bound to the class, rather than an instance of the class:

class Negator:
    @singledispatchmethod
    @classmethod
    def neg(cls, arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    @classmethod
    def _(cls, arg: int):
        return -arg

    @neg.register
    @classmethod
    def _(cls, arg: bool):
        return not arg

The same pattern can be used for other similar decorators: @staticmethod, @abstractmethod, and others.

Nouveau dans la version 3.8.

functools.update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

Met à jour la fonction wrapper pour ressembler à la fonction wrapped. Les arguments optionnels sont des n-uplets pour spécifier quels attributs de la fonction originale sont assignés directement aux attributs correspondants sur la fonction englobante et quels attributs de la fonction englobante sont mis à jour avec les attributs de la fonction originale. Les valeurs par défaut de ces arguments sont les constantes au niveau du module WRAPPER_ASSIGNMENTS (qui assigne __module__, __name__, __qualname__, __annotations__ et __doc__, la chaîne de documentation, depuis la fonction englobante) et WRAPPER_UPDATES (qui met à jour le __dict__ de la fonction englobante, c'est-à-dire le dictionnaire de l'instance).

Pour autoriser l'accès à la fonction originale pour l'introspection ou à d'autres fins (par ex. outrepasser l'accès à un décorateur de cache comme lru_cache()), cette fonction ajoute automatiquement un attribut __wrapped__ qui référence la fonction englobée.

La principale utilisation de cette fonction est dans les décorateurs qui renvoient une nouvelle fonction. Si la fonction crée n'est pas mise à jour, ses métadonnées refléteront sa définition dans le décorateur, au lieu de la définition originale, métadonnées souvent bien moins utiles.

update_wrapper() peut être utilisé avec des appelables autres que des fonctions. Tout attribut défini dans assigned ou updated qui ne sont pas l'objet englobé sont ignorés (cette fonction n'essaiera pas de les définir dans la fonction englobante). AttributeError est toujours levée si le fonction englobante elle même a des attributs non existants dans updated.

Modifié dans la version 3.2: The __wrapped__ attribute is now automatically added. The __annotations__ attribute is now copied by default. Missing attributes no longer trigger an AttributeError.

Modifié dans la version 3.4: L'attribut __wrapped__ renvoie toujours la fonction englobée, même si cette fonction définit un attribut __wrapped__. (voir bpo-17482)

@functools.wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

Ceci est une fonction d'aide pour appeler update_wrapper() comme décorateur de fonction lors de la définition d'une fonction englobante. C'est équivalent à partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated). Par exemple :

>>> from functools import wraps
>>> def my_decorator(f):
...     @wraps(f)
...     def wrapper(*args, **kwds):
...         print('Calling decorated function')
...         return f(*args, **kwds)
...     return wrapper
...
>>> @my_decorator
... def example():
...     """Docstring"""
...     print('Called example function')
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'

Sans l'utilisation de cette usine à décorateur, le nom de la fonction d'exemple aurait été 'wrapper', et la chaîne de documentation de la fonction example() originale aurait été perdue.

Objets partial

Les objets partial sont des objets appelables créés par partial(). Ils ont trois attributs en lecture seule :

partial.func

Un objet ou une fonction appelable. Les appels à l'objet partial seront transmis à func avec les nouveaux arguments et mots-clés.

partial.args

Les arguments positionnels qui seront ajoutés avant les arguments fournis lors de l'appel d'un objet partial.

partial.keywords

Les arguments nommés qui seront fournis quand l'objet partial est appelé.

partial objects are like function objects in that they are callable, weak referenceable, and can have attributes. There are some important differences. For instance, the __name__ and __doc__ attributes are not created automatically. Also, partial objects defined in classes behave like static methods and do not transform into bound methods during instance attribute look-up.