DEV Community

Cover image for LEGB Rule for Python Scope
Z. QIU
Z. QIU

Posted on

LEGB Rule for Python Scope

Though I have coded in Python for pretty long time, the concept of scopes in Python is still a little unclear for me. Today, I studied a little bit the scopes in Python. To better illustrate what I've understood, I drew a sketch as shown below.

Alt Text

The 4 letters in LEGB stand for Local, Enclosing, Global, and Built-in. Python interpreter shall look up a variable content sequentially in following order: local -> enclosing -> global -> built-in.

Below are some snapshots of my tests:

Alt Text

refrence of this post:

  1. https://realpython.com/python-scope-legb-rule/

Top comments (0)