Scope (ขอบเขต) ใน Python ควบคุมโดย Namespace ตัวแปรถูกค้นหาตามลำดับ LEGB Rule:
- L - Local: ตัวแปรที่กำหนดในฟังก์ชัน/แลมบ์ดา (ไม่ได้ประกาศ global)
- E - Enclosing: ตัวแปรในฟังก์ชันภายนอกที่ห่อหุ้ม (Nested Functions) เรียกจากในออกไป
- G - Global (Module): ตัวแปรระดับบนสุดของโมดูล หรือที่ประกาศ
globalในฟังก์ชัน - B - Built-in: ชื่อสำรองของ Python (
open,range,Exception, ...)
ตัวอย่าง
x = 'global' # G
def outer():
x = 'enclosing' # E
def inner():
x = 'local' # L
print(x) # พิมพ์ 'local'
inner()
print(x) # พิมพ์ 'enclosing'
outer()
print(x) # พิมพ์ 'global'
คำสั่งควบคุม Scope
global x→ ใช้/แก้ไขตัวแปรระดับ Module (G)nonlocal x→ ใช้/แก้ไขตัวแปรระดับ Enclosing (E) (Python 3+)