How to declare global variables in Python


Python

In this tutorial we will learn about different terminologies related to declaring variables (local and global) in Python. You need to be familiar with namespace, scope and functions to be able to declare local and/or global variables in python scripts. We will cover these in details, I will try to give as much as details as possible to help even a beginner understand the basic concepts of Python programming.

 

Python version from my environment

# python3 --version
Python 3.6.8

 

Define a function with def

  • You should be familiar with what are functions and how we can define a function in Python
  • Functions are the primary and most important method of code organization and reuse in Python.
  • As a rule of thumb, if you anticipate needing to repeat the same or very similar code more than once, it may be worth writing a reusable function.
  • Functions can also help make your code more readable by giving a name to a group of Python statements.
  • Functions are declared with the def keyword and returned from with the return keyword:
  • Python comes with multiple in-build functions

In this example we have a simple function

# cat /tmp/define_functions.py
#!/usr/bin/env python3

def do_nothing():
    pass

# Call the do_nothing function
do_nothing()
  • Even for a function with no parameters like this one, you still need the parentheses () and the colon : in its definition
  • The next line needs to be indented, you cannot use TAB, use space character to indent the next line
  • Python requires the pass statement to show that this function does nothing. It’s the equivalent of This page intentionally left blank

I will execute this script

# python3 /tmp/define_functions.py

There is no output as expected.

Now we will print some thing on the screen

#!/usr/bin/env python3

def hello_world():
    print('hello world')

# Call the hello_world function
hello_world()

The output from this script will execute the print() function:

# python3 /tmp/define_functions.py
hello world

We will go one step ahead and use function to return boolean True/False value and further use this in if and else condition

#!/usr/bin/env python3

def agree():
    return True

if agree():
    print('Good, you agree')
else:
    print('I hope you agree next time')

The output from this script:

# python3 /tmp/define_functions.py
Good, you agree

So I hope now since you have a basic idea of functions in Python

 

What are Namespaces and Scope in Python

  • Python programs have various namespaces sections within which a particular name is unique and unrelated to the same name in other namespaces
  • Each function defines its own namespace.
  • If you define a variable called x in a main program and another variable called x in a function, they refer to different things.
  • But the walls can be breached: if you need to, you can access names in other namespaces in various ways.
  • Functions can access variables in two different scopes: global and local.
  • An alternative and more descriptive name describing a variable scope in Python is a namespace.
  • Any variables that are assigned within a function by default are assigned to the local namespace.

We will understand about this better in next chapters and examples.

 

Declare Local Variable

  • A local variable’s identifier has local scope.
  • It’s "in scope" only from its definition to the end of the function’s block.
  • It "goes out of scope" when the function returns to its caller.
  • So, a local variable can be used only inside the function that defines it.

Let us take this simple python script

#!/usr/bin/env python3

def func():
    # declare local variable inside the function
    a = []
    for i in range(5):
        a.append(i)

func()
print(a)

Here when function func() is called the empty list "a" is created, five elements are appended, and then "a" is destroyed when the function exits.
The output of this script will fail to print content of variable "a"

# python3 /tmp/define_namespace.py
Traceback (most recent call last):
  File "/tmp/define_namespace.py", line 9, in <module>
    print(a)
NameError: name 'a' is not defined

 

Declare Global Variable

  • Identifiers defined outside any function (or class) have global scope, these may include functions, variables and classes.
  • Variables with global scope are known as global variables.
  • Identifiers with global scope can be used in a .py file or interactive session anywhere after they’re defined.

We will use our existing example and declare a outside in the main script as global variable

#!/usr/bin/env python3

# declare global variable outside the function
a = []

def func():
    for i in range(5):
	# Access global variable inside the function
        a.append(i)

func()
print(a)

The output from this script will print the content of variable "a" as a was defined under global scope (outside function)

# python3 /tmp/define_variable.py
[0, 1, 2, 3, 4]

 

Access and Modify Global Variable from a function

  • In our last example we didn't modified the value of the variable
  • By default, you cannot modify a global variable in a function, when you first assign a value to a variable in a function’s block, python creates a new local variable
  • For example in this sample python script, I have defined a global variable
  • Next I will access this variable inside access_global() function and print the value
  • Then I will modify the value of var from 10 to 20 inside modify_global_var() function
  • Later I will call modify_global_var() function to check the value of var variable
  • At the end I will again print the value of var to check if the content of global variable was modified
How to declare global variables in Python
Declare and Access Global Variable in Python

 

Now when we execute the script the local var shadows the global var inside modify_global_var(), making it inaccessible in the scope of the function’s block. But our last print function shows that variable var still exists and has its original value (10) after function modify_global_var() is executed.

# python3 /tmp/define_variable.py
Value of var within function is:  10
New value of var after modification:  20
Original value of var is:  10

If you don’t use global within a function, Python uses the local namespace and the variable is local. It goes away after the function completes.

So to modify a global variable in a function’s block, you must use a global statement to declare that the variable is defined in the global scope:

How to declare global variables in Python
Modify Global Variable Value

 

We will re-run this python script:

# python3 /tmp/define_variable.py
Value of var within function is:  10
New value of var after modification:  20
Original value of var is:  20

So now the value of var is retained even after modify_global_var() function is executed

 

Python provides two functions to access the contents of your namespaces:

  • locals() returns a dictionary of the contents of the local namespace.
  • globals() returns a dictionary of the contents of the global namespace.

For example we have defined a new local variable for var within access_global() function and then use locals to print the available local variable

#!/usr/bin/env python3

# Define Global Variable
var = 10

def access_global():
   var=20
   print('Value of var within function is: ', var)
   print('locals:', locals())

# Call access_global function
access_global()

The output from this script

# python3 /tmp/define_variable.py
Value of var within function is:  20
locals: {'var': 20}

 

Conclusion

So I hope you understood the difference between local and global variables. In this tutorial we learned about different terminologies from Python programming such as functions, namespaces, scopes and declaring variables.

The basic rule is that any variable which is assigned in the main script would be global variable while if it is assigned within the function then it would be considered as local variable unless you explicitly use global keyword

Lastly I hope this tutorial on variables, namespace and scope in Python programming was helpful. So, let me know your suggestions and feedback using the comment section.

 

Deepak Prasad

Deepak Prasad

Deepak Prasad is the founder of GoLinuxCloud, bringing over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, Networking, and Security. His extensive experience spans development, DevOps, networking, and security, ensuring robust and efficient solutions for diverse projects.

Certifications and Credentials:

  • Certified Kubernetes Application Developer (CKAD)
  • Go Developer Certification
  • Linux Foundation Certified System Administrator (LFCS)
  • Certified Ethical Hacker (CEH)
  • Python Institute PCAP (Certified Associate in Python Programming)
You can connect with him on his LinkedIn profile and join his Facebook and LinkedIn page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

1 thought on “How to declare global variables in Python”

Leave a Comment