← Back to Python Course | Chapter 11: Advanced Python | Lesson 11 of 12

Python functools

functools functions के साथ काम करने के लिए helpers का एक toolbox है, जैसे काम दोहराने से बचने के लिए जवाब याद रखना। यह caching और arguments को पहले से भरने जैसे shortcuts देता है।
Syntax
python
from functools import reduce, partial, lru_cache

@lru_cache(maxsize=None)
def function_name(parameter):
    # cached result

new_function = partial(function_name, argument)

lru_cache से Caching

@lru_cache decorator किसी function के return value को उसके exact arguments के मुक़ाबले memoize कर देता है, ताकि एक जैसे inputs वाली बार-बार calls recomputation को पूरी तरह skip करके तुरंत cached result लौटा दें।

यह plain recursive Fibonacci जैसे naive exponential-time recursive functions को एक ही decorator से तेज़ linear-time functions में बदल देता है।

उदाहरण: Caching with lru_cache

python
from functools import lru_cache

@lru_cache  # caches results per set of arguments
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(30))  # fast thanks to cached repeated subcalls

partial से Partial Functions

partial() एक function और उसके कुछ arguments लेता है और एक नया callable लौटाता है जिसमें वे arguments पहले से lock हैं, और call करते समय सिर्फ़ बाकी arguments चाहिए होते हैं।

यह किसी general-purpose function को हाथ से wrapper def लिखे बिना एक narrower function में specialize करने का साफ़-सुथरा तरीका है।

उदाहरण: Partial Functions with partial

python
from functools import partial

def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)  # locks in exponent=2
print(square(5))  # only base is still needed

cmp_to_key से Custom Sorting

cmp_to_key() पुरानी style के two-argument comparison functions (जो negative, zero, या positive लौटाते हैं) को उन single-argument key functions में bridge करता है जिन्हें modern Python में sorted() और list.sort() expect करते हैं।

यह मुख्यतः उस legacy comparison logic को adapt करने के लिए मौजूद है जो Python 3 के key-function-only sorting API से पुराना है।

उदाहरण: Custom Sorting with cmp_to_key

python
from functools import cmp_to_key

def compare(a, b):  # old-style comparator: negative, zero, or positive
    return a - b

nums = [3, 1, 2]
print(sorted(nums, key=cmp_to_key(compare)))  # adapts it into a modern key function

wraps से Decorators को Wrap करना

@wraps को किसी custom decorator के अंदरूनी wrapper function पर apply किया जाता है, और यह original function का __name__, __doc__, और अन्य metadata wrapper पर copy कर देता है।

इसके बिना, decorated functions असली function की बजाय wrapper के अपने नाम और docstring को गुमराह करके report करेंगे, जो introspection tools को तोड़ता है और debugging को उलझाता है।

उदाहरण: Wrapping Decorators with wraps

python
from functools import wraps

def log(func):
    @wraps(func)  # copies func's __name__ and __doc__ onto wrapper
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@log
def greet():
    """Greets the user."""
    print("hi")

print(greet.__name__, greet.__doc__)  # reports greet's real name and docstring

reduce से Values जोड़ना

reduce() किसी दो-argument वाले function को एक running accumulator और sequence के हर अगले item पर बार-बार apply करता है, पूरी sequence को एक अंतिम value में समेट देता है।

यह किसी list का योग निकालने या maximum ढूँढने जैसे patterns के पीछे का general-purpose tool है, हालाँकि उन specific मामलों के लिए Python के built-in sum() और max() आमतौर पर ज़्यादा साफ़ होते हैं।

उदाहरण: Accumulating Values with reduce

python
from functools import reduce

numbers = [1, 2, 3, 4]
total = reduce(lambda a, b: a + b, numbers)  # collapses the list into one accumulated value
print(total)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.