الـ Decorators في بايثون: سحر تعديل الدوال دون لمس كودها!

مرحباً بك في عالم الـ Decorators في بايثون! في هذا الدرس سنتعلم كيف تجعل كودك أكثر أناقة وكفاءة باستخدام هذه الميزة القوية. الـ Decorators تسمح لك بـ"تزيين" أو تعديل سلوك الدوال والكلاسات دون الحاجة لتغيير الكود الأصلي لها، مما يحقق مبدأ فصل المسؤوليات في البرمجة.

ما هي الـ Decorators؟

ببساطة، الـ Decorator هو دالة تستقبل دالة أخرى كمدخل، وتضيف إليها وظائف جديدة، ثم تعيد دالة معدلة.

تعتمد الـ Decorators على مفهومين أساسيين في بايثون:

  1. الدوال كـ Objects (First-Class Functions): يمكن تمرير الدالة كـ Parameter لدالة أخرى أو إرجاعها كقيمة.
  2. الدوال المتداخلة (Nested Functions): إمكانية تعريف دالة داخل دالة أخرى.

فكر في الـ Decorator كـ"غلاف" أو "إطار" يحيط بالدالة الأصلية؛ حيث ينفذ كوداً معيناً قبل استدعاء الدالة، ثم يستدعي الدالة نفسها، ثم ينفذ كوداً إضافياً بعدها.

البنية الأساسية للـ Decorator

لفهم كيف يعمل الـ Decorator من الداخل، انظر إلى هذا الهيكل البسيط:

def my_decorator(func):  # Main decorator: receives the function to be modified
    def wrapper():        # Wrapper function: executes additions and calls the original
        print("Executing code before the original function")

        func()  # Call the passed function

        print("Executing code after the original function")

    return wrapper  # Return the wrapper function to replace the original function

شرح المكونات:

  • my_decorator: هو المصنع الذي يصنع النسخة المعدلة من الدالة.
  • func: هي الدالة الأصلية التي نريد إضافة ميزات لها.
  • wrapper: هي الدالة "الوسيطة" التي تدمج السلوك الجديد مع السلوك القديم.

تطبيق عملي: أول Decorator لك!

لنطبق هذا المفهوم على دالة ترحيب بسيطة:

def say_hello():
    print("Hello! Welcome to Codex Academy.")

# Manual way to apply the decorator
decorated_function = my_decorator(say_hello)

# Call the function after decorating it
decorated_function()

مخرجات التشغيل:

 Execute code before the original function
Hello! Welcome to Codex Academy.
 Execute code after the original function

السكر النحوي: @decorator

بدلاً من تعيين الدالة يدوياً كما فعلنا سابقاً، توفر بايثون رمز @ (Syntactic Sugar) لجعل الكود أكثر نظافة واحترافية:

@my_decorator
def say_hello():
    print("Hello! Welcome.")

# Direct call
say_hello()

عند وضع @my_decorator فوق الدالة، تقوم بايثون تلقائياً بتنفيذ: say_hello = my_decorator(say_hello).

مثال واقعي: Decorator قياس الوقت

تستخدم الـ Decorators بكثرة في "التسجيل" (Logging) و"قياس الأداء". إليك Decorator يحسب زمن تنفيذ أي دالة:

import time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()  # Record start time
        result = func(*args, **kwargs)  # Execute function and save result
        end_time = time.time()    # Record end time

        duration = end_time - start_time
        print(f"⏱ Function {func.__name__} took {duration:.4f} seconds")
        return result
    return wrapper

@timer_decorator
def heavy_process():
    print("Processing data...")
    time.sleep(1.5)  # Simulate a time-consuming process
    print("Processing completed successfully!")

heavy_process()

Decorators للدوال ذات الـ Parameters

إذا كانت الدالة الأصلية تستقبل Inputs (مثل اسم المستخدم أو أرقام)، يجب أن يكون الـ Decorator مرناً لاستقبال أي عدد من الـ Parameters باستخدام *args و **kwargs:

def logger_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function: {func.__name__} with arguments: {args}")
        return func(*args, **kwargs)
    return wrapper

@logger_decorator
def add_numbers(a, b):
    return a + b

@logger_decorator
def greet(name, greeting="Hello"):
    return f"{greeting} {name}!"

print(add_numbers(10, 20))
print(greet("Sarah", greeting="Hi"))

لماذا استخدمنا *args و **kwargs؟

  • *args: لاستقبال أي عدد من الـ Parameters الموضعية (Positional Arguments).
  • **kwargs: لاستقبال أي عدد من الـ Parameters المسماة (Keyword Arguments). هذا يجعل الـ Decorator "عاماً" يصلح لأي دالة بغض النظر عن Inputs الخاصة بها.

Decorators متعددة ومتداخلة

يمكنك وضع أكثر من Decorator فوق دالة واحدة. يتم التنفيذ من الأعلى إلى الأسفل عند التغليف، ومن الداخل إلى الخارج عند التنفيذ:

def bold(func):
    def wrapper():
        return "<b>" + func() + "</b>"
    return wrapper

def italic(func):
    def wrapper():
        return "<i>" + func() + "</i>"
    return wrapper

@bold
@italic
def get_text():
    return "code text"

print(get_text())
# Result: <b><i>code text</i></b>

في هذا المثال، تم تغليف الدالة بـ italic أولاً، ثم غُلفت النتيجة بـ bold.

ملخص الدرس

  • الـ Decorators: هي دوال تغلف دوالاً أخرى لإضافة سلوك جديد دون تعديل الكود الأصلي.
  • الرمز @: طريقة مختصرة لتطبيق الـ Decorator على الدالة.
  • المرونة: نستخدم *args و **kwargs لضمان عمل الـ Decorator مع أي دالة مهما كانت its Parameters.
  • التسلسل: عند استخدام عدة Decorators، يتم التطبيق من الأسفل (الأقرب للدالة) إلى الأعلى.