Python Variables Scope

Python Variables Scope

Daily dose of code...

Learn what variable scopes are all about and get familiar with the 'LEGB' rule.

Variable

A variable is a label or a name given to a certain location in memory. This location holds the value you want your program to remember, for use later on. What's great in Python is that you do not have to explicitly state what the type of variable you want to define is - it can be of any type (string, integer, float, etc.). To create a new variable in Python, you simply use the assignment operator (=, a single equals sign) and assign the desired value to it.

first_string_var = "First String"  
first_int_var = 1
total = 1 + 2 * 3        

Assigning an initial value to a variable is called initializing. The initialized variable: first_string_var with a string value of First String and variable first_int_var with an integer or numeric value of 1. The part to the left of the assignment operator is the variable name, and the right side is its value. The right-hand side can also be an arithmetic operation - in which case, it will be evaluated before the assignment occurs.

Python has some rules that you must follow when creating a variable:

  • It may only contain letters (uppercase or lowercase), numbers or the underscore character _.
  • It may not start with a number.
  • It may not be a keyword (you will learn about them later on).If you do not follow these rules, you will get an error.

In programming languages, variables need to be defined before using them. These variables can only be accessed in the area where they are defined, this is called scope. You can think of this as a block where you can access variables.

The logic behind scope is that scope determines accessibility of variables, functions, objects, and so on. It is directly depends on where you creat them.

When learning to program, the first set of operations you want to be able to complete are inputs, outputs, and storage of data. Almost every programming problem involves taking some form of input from a user, computing logic, then outputting some sort of end result to the user. The goal of this article is to introduce the syntax for these operations, and explain exactly what happens when we run them.

The concept of scope rules how variables and names are looked up in your code. It determines the visibility of a variable within the code. The scope of a name or variable depends on the place in your code where you create that variable.


The Python scope concept is generally presented using a rule known as the LEGB rule.

In order to understand actually how the scope resolution happening in Python, we should analyze the LEGB rule because, it is the sequence of names(variables, functions, objects and so on) that Python resolves in a program.

LEGB stands for :

(L) → Local or(function) scope -

It is the code block or body of any Python function or lambda expression. This Python scope contains the names of thr variables that are defined inside the function. These names will only be visible from the code of the function. It’s created at function call, not at function definition, so you’ll have as many different local scopes as function calls. This is true even if you call the same function multiple times, or recursively. Each call will result in a new local scope being created.

These exist only while the function is executing. We cannot access them outside the function.

(E) →Enclosed scope or nonlocal scope: This case is special and occurs only when we have nested functions. The variables in the outer function are neither global nor local to the inner function. These have nonlocal scope.

If the local scope is an inner or a nested function, then the enclosing scope is the scope of the outer or enclosing function. This scope contains the names that you define in the enclosing function. The names in the enclosing scope are visible from the code of the inner and enclosing functions.

(G) →Global or module scope is the top-most scope in a Python program, script, or module. This Python scope contains all the names that you define at the top level of a program or a module. Names in this Python scope are visible from everywhere in your code.

This is the scope of the variables that are created outside the functions. These can be accessed from any part of the program.

(B) →Built-in scope This is the scope of all the keywords. This is the largest scope. These load when the interpreter starts and we can access them from any part.

It is a special Python scope that’s created or loaded whenever a script is run or open an interactive session. This scope contains names such as keywords, functions, exceptions, and other attributes that are built into Python. Names in this Python scope are also available from everywhere in your code. It’s automatically loaded by Python when you run a program or script.

the LEGB rule displays the sequence of how Python resolves names(variables, functions, objects and so on), it is so important to remember it from(highest(L) to lowest(B)).

We have at least three Python scopes: built-in, global, and local. Accordingly, we have the corresponding namespaces. The enclosed scoped variables come under nested local namespace.

These decide which reference of the variable is given preference while accessing its value. This is called the “LEGB” rule. According to this, the preference order is Local-> Enclosed-> Global -> Built-in.

In programming, the scope of a name defines the area of a program in which you can unambiguously access that name, such as variables, functions, objects, and so on. A name will only be visible to and accessible by the code in its scope. Several programming languages take advantage of scope for avoiding name collisions and unpredictable behaviors. Most commonly, you’ll distinguish two general scopes:

  1. Global scope: The names that you define in this scope are available to all your code.
  2. Local scope: The names that you define in this scope are only available or visible to the code within the scope.

Scope came about because early programming languages (like BASIC) only had global names. With this kind of name, any part of the program could modify any variable at any time, so maintaining and debugging large programs could become a real nightmare. To work with global names, you’d need to keep all the code in mind at the same time to know what the value of a given name is at any time. This was an important side-effect of not having scopes.

When using a language that implements scope, there’s no way to access all the variables in a program at all locations in that program. In this case, your ability to access a given name will depend on where you’ve defined that name.

Local (or function) scope

Whenever you define a variable within a function, its scope lies ONLY within the function. It is accessible from the point at which it is defined until the end of the function and exists for as long as the function is executing (Source). Which means its value cannot be changed or even accessed from outside the function. Let's take a simple example:

Local scope refers to the name(variable, function and so on) that is defined inside the function. It means it is accessible within the point at it is defined until the end of the function. That particular scope can’t be modified or even accessed outside of the function. Local scope variables can only be accessed within its block.

As an example:


a = 10
def function():
  print(“Hello”)
  b = 20
function()
print(a)
print(b)        

Example 2

def print_number():
    first_num = 1
    # Print statement 1
    print("The first number defined is: ", first_num)

print_number()
# Print statement 2
print("The first number defined is: ", first_num)        

Global Scope

The variables that are declared in the global scope can be accessed from anywhere in the program. Global variables can be used inside any functions. We can also change the global variable value.

Msg = “This is declared globally”

def function():
  #local scope of function
  print(Msg)

function()        

Output

This is declared globally        

But, what would happen if you declare a local variable with the same name as a global variable inside a function?

 msg = “global variable”

def function():
  #local scope of function
  msg = “local variable”
  print(msg)

function()
print(msg)        

Output

local variable
global variable        

if we declare a local variable with the same name as a global variable then the local scope will use the local variable.

If you want to use the global variable inside local scope then you will need to use the “global” keyword.

Enclosing Scope

What if we have a nested function (function defined inside another function)? How does the scope change? Let's see with the help of an example

def outer():
    first_num = 1
    def inner():
        second_num = 2
        # Print statement 1 - Scope: Inner
        print("first_num from outer: ", first_num)
        # Print statement 2 - Scope: Inner
        print("second_num from inner: ", second_num)
    inner()
    # Print statement 3 - Scope: Outer
    print("second_num from inner: ", second_num)

outer()        

Output


<ipython-input-4-13943a1eb01e> in <module>
     11     print("second_num from inner: ", second_num)
     12
---> 13 outer()


<ipython-input-4-13943a1eb01e> in outer()
      9     inner()
     10     # Print statement 3 - Scope: Outer
---> 11     print("second_num from inner: ", second_num)
     12
     13 outer()


NameError: name 'second_num' is not defined        

There is an error because we cannot access second_num from outer() (# Print statement 3). It is not defined within that function. However, we can access first_num from inner() (# Print statement 1), because the scope of first_num is larger, it is within outer().

This is an enclosing scope. Outer's variables have a larger scope and can be accessed from the enclosed function inner().

Built-in Scope

This is the widest scope that exists! All the special reserved keywords fall under this scope. We can call the keywords anywhere within our program without having to define them before use.

Keywords are simply special reserved words. They are kept for specific purposes and cannot be used for any other purpose in the program. These are the keywords in Python:

We cannot use a keyword as a variable name, function names or any other identifier. Keywords in Python are reserved words.


要查看或添加评论,请登录

社区洞察

其他会员也浏览了