Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python functools singledispatch() Function



The Pythonsingledispatch() function perform operations regardless of any datatype. If we want a function to behave differently based on the argument type, this decorator allows us to write functions that dispatch operations based on the type of the argument.

If the implementations are denoted with types then the decorator automatically determines the argument type. Otherwise, the type itself is passed as an argument to the decorator.

Syntax

Following is the syntax for thesingledispatch() function.

@singledispatch

Parameters

Thesingledispatch() decorator is used on this function to handle the default case.

Return Value

This decorator returns the specific type of a function to handle the default case.

Example 1

This code usessingledispatch() function to determine different data types. This function processes specifies integers, strings, and other types uniquely.

from functools import singledispatch@singledispatchdef process_data(data):    return f"processing for {data}"@process_data.register(int)def _(data):    return f"integer: {data}"@process_data.register(str)def _(data):    return f"string: {data}"print(process_data(25))  print(process_data("Welcome to Tutorialspoint"))   print(process_data([4, 3, 6]))

Output

The result is generated as follows −

integer: 25string: Welcome to Tutorialspointprocessing for [4, 3, 6]

Example 2

In the below example, we are managing different data types usingsingledispatch() function. This function has specific implementations for list and dictionaries.

from functools import singledispatch@singledispatchdef process_data(data): return f"processing for {data}"@process_data.register(int)def _(data): return f"integer: {data}"@process_data.register(float)def _(data): return f"float: {data}"print(process_data(10)) print(process_data(10.5)) print(process_data(1.22))

Output

The code is generated as follows −

integer: 10float: 10.5float: 1.22

Example 3

Here, we are specifying the different collection types in thissingledispatch() function. The process_data function is decorated with this function to determine data types.

from functools import singledispatch@singledispatchdef process_data(data): return f"processing for {data}"@process_data.register(list)def _(data): return f"list: {data}"@process_data.register(dict)def _(data): return f"dict: {data}"print(process_data([4, 7, 9, 3]))  print(process_data({"key": "value"})) print(process_data(64))

Output

The output is obtained as follows −

list: [4, 7, 9, 3]dict: {'key': 'value'}processing for 64
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp