Scope

In this lesson, you'll learn about the scope of variables in Python.

Introduction to scope

The scope of a name is the part of the program in which the name has meaning and can be used. Python’s scope rules are unusual because they follow an “LEGB rule”: Local, Enclosed, Global, Built-in.

To understand this rule, it helps to remember that:

  1. Variables are defined by being assigned a value.
  2. Functions/methods may be nested within other functions/ methods.

When dealing with the scope of a variable in Python, keep in mind the following point:

  • Variables may be declared global or nonlocal by a statement in the form global var1,...,varN or nonlocal var1,...,varN. The declaration must precede any use of the variable.

Types of scopes

Following are four different types of scope present in Python:

  • Local: A variable is local to a function if it is assigned a value within that function, and it is not declared otherwise.

  • Enclosed: A variable in a function can refer to a variable declared in an enclosing function, provided either of the following conditions are met:

    1. The variable is not assigned a value in this function.
    2. It is declared in a nonlocal statement.
  • Global: A variable declared at the top level (not in a function or method) is global, and it can be referenced throughout the program. A variable in a function can refer to a global variable, provided either of the following conditions are met:

    1. The variable is not assigned a value in this function or in an enclosing function.
    2. It is declared in a global statement.
  • Built-in: A variable not declared otherwise in the program might be a built-in variable. Some examples are list, print, and divmod.

Get hands-on with 1400+ tech skills courses.