فهم نطاقات المتغيرات (Scopes) في بايثون: دليلك الشامل للمبتدئين

اليوم سنتعرف على مفهوم بالغ الأهمية في البرمجة بشكل عام وفي بايثون بشكل خاص: نطاقات المتغيرات أو Scopes. إذا كنت قد واجهت رسالة خطأ تقول NameError: name 'x' is not defined من قبل، فهذا الدرس سيساعدك على فهم سبب هذا الخطأ وكيف تتجنبه.

ما هو النطاق (Scope)؟

النطاق هو المنطقة أو السياق في برنامجك حيث يتم تعريف المتغير ويمكن الوصول إليه. تخيل أن النطاق يشبه الغرف في منزلك:

  • بعض الأشياء موجودة في غرفة النوم (محلية) ولا يمكن رؤيتها من الغرفة الأخرى
  • بعض الأشياء موجودة في الصالة (عامة) ويمكن للجميع رؤيتها

في بايثون، النطاق يحدد أين يمكنك استخدام متغير معين في الكود.

# This is a global variable (in the global scope)
global_var = "I am a global variable"

def my_function():
    # This is a local variable (inside the function's local scope)
    local_var = "I am a local variable"
    print(global_var) # Global variable is accessible
    print(local_var) # Local variable is accessible

my_function()
print(global_var) # Global variable is accessible
# print(local_var) # Error! Local variable is not accessible outside the function

أنواع النطاقات في بايثون

1. النطاق المحلي (Local Scope)

هو النطاق داخل الدالة. المتغيرات المعرفة داخل دالة تكون محلية وتوجد فقط داخل تلك الدالة.

def calculate_sum(a, b):
    result = a + b  # 'result' is a local variable
    return result

# print(result) # Error! 'result' is unknown outside the function

2. النطاق العام (Global Scope)

هو النطاق خارج أي دالة. المتغيرات المعرفة هنا تكون عامة ويمكن الوصول لها من أي مكان في البرنامج.

website_name = "Codex Academy"  # Global variable

def welcome_message():
    message = "Welcome to " + website_name # Global variable is accessible
    return message

print(welcome_message())

3. النطاق غير المحلي (Nonlocal Scope)

يظهر عندما يكون لدينا دوال داخل دوال (دوال متداخلة).

def outer_function():
    outer_var = "I am in the outer scope"

    def inner_function():
        nonlocal outer_var  # Use nonlocal to access the outer function variable
        outer_var = "Modified from the inner function"

    inner_function()
    print(outer_var)  # Will print: "Modified from the inner function"

outer_function()

قاعدة LEGB: ترتيب البحث عن المتغيرات

عندما تطلب بايثون قيمة متغير، تبحث فيه بالترتيب التالي:

  1. Local - النطاق المحلي (داخل الدالة الحالية)
  2. Enclosing - النطاق المحيط (في الدوال الخارجية)
  3. Global - النطاق العام
  4. Built-in - النطاق المدمج (الدوال المضمنة في بايثون)
x = "global"  # Global scope

def test_scope():
    x = "local"  # Local scope
    print(x)    # Will print: "local" (takes value from local scope)

test_scope()
print(x)        # Will print: "global" (takes value from global scope)

الأخطاء الشائعة وكيفية تجنبها

الخطأ: محاولة تعديل متغير عام بدون كلمة global

counter = 0

def increment():
    # counter += 1 # Error! Cannot modify global variable directly
    global counter # Correct solution
    counter += 1

increment()
print(counter)  # Will print: 1

الخطأ: الخلط بين المتغيرات المحلية والعامة

name = "Ahmed"

def change_name():
    name = "Mohamed"  # This creates a new local variable, does not modify the global variable
    print("Inside function:", name)

change_name()  # Prints: Inside function: Mohamed
print("Outside function:", name)  # Prints: Outside function: Ahmed

نصائح عملية لاستخدام النطاقات

  1. استخدم متغيرات محلية قدر الإمكان لتجنب التضارب
  2. قلل استخدام المتغيرات العامة إلا عند الضرورة
  3. استخدم أسماء متغيرات واضحة لتجنب الخلط
  4. افهم دائماً أين عرفت المتغير قبل استخدامه
# Good example of using scopes
def calculate_area(radius):
    pi = 3.14159  # Appropriate local variable
    area = pi * radius ** 2
    return area

# Using the function correctly
circle_area = calculate_area(5)
print("Circle area:", circle_area)

خلاصة الدرس

  • النطاق المحلي: داخل الدالة، متاح فقط داخلها
  • النطاق العام: خارج الدوال، متاح في كل مكان
  • النطاق غير المحلي: للدوال المتداخلة، نستخدم nonlocal
  • قاعدة LEGB: ترتيب البحث عن المتغيرات
  • تجنب الأخطاء: استخدام global عند تعديل المتغيرات العامة