Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Tutorial_ Global vs. Local Variables and Namespaces

The document discusses the concepts of global, local, and nonlocal variables in Python, emphasizing that variables are local by default unless explicitly declared as global. It explains how to use global variables within functions and the implications of using the nonlocal keyword in nested functions. Additionally, it highlights best practices for variable usage to avoid ambiguity and errors in Python programming.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Tutorial_ Global vs. Local Variables and Namespaces

The document discusses the concepts of global, local, and nonlocal variables in Python, emphasizing that variables are local by default unless explicitly declared as global. It explains how to use global variables within functions and the implications of using the nonlocal keyword in nested functions. Additionally, it highlights best practices for variable usage to avoid ambiguity and errors in Python programming.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Namespaces


Next Chapter: Decorators

Global, Local and nonlocal Variables


The way Python uses global and local variables is maverick. While in many or most other programming languages variables are treated as global if not otherwise declared,
Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally Follow Bernd Klein,
bad practice and should be avoided. In most cases where you are tempted to use a global variable, it is better to utilize a parameter for getting a value into a function or the author of this
return a value to get it out. Like in many other program structures, Python also imposes good programming habit by design. website, at Google+:
Bernd Klein on
So when you define variables inside a function definition, they are local to this function by default. This means that anything you will do to such a variable in the body of the Google
Python 3 function will have no effect on other variables outside of the function, even if they have the same name. This means that the function body is the scope of such a variable,
Tutorial i.e. the enclosing context where this name with its values is associated. Bernd Klein on
Facebook
The Origins of All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration.
Python
Starting with Just to make things clear: Variables don't have to be and can't be declared in the way they are declared in programming languages like Java or C. Variables in Python are Search this website:
Python: The implicitly declared by defining them, i.e. the first time you assign a value to a variable, this variable is declared and has automatically the data type of the object which has
Interactive Shell to be assigned to it. If you have problems understanding this, please consult our chapter about data types and variables, see links on the left side. Go
Executing a
Script This topic in German
Global and local Variables in Functions / Deutsche
Indentation
Data Types and Übersetzung: Globale
In the following example, we want to demonstrate, how global values can be used inside the body of a function: und lokale Variablen
Variables
und Namensräume in
Operators def f(): Python
Sequential Data print(s)
Types: Lists and s = "I love Paris in the summer!"
f() Python 3
Strings
List This is a tutorial in
The variable s is defined as the string "I love Paris in the summer!", before calling the function f(). The body of f() consists solely of the "print(s)" statement. As there is no local variable s, i.e. no assignment to s,
Manipulations the value from the global variable s will be used. So the output will be the string "I love Paris in the summer!". The question is, what will happen, if we change the value of s inside of the function f()? Will it affect Python3, but this
Shallow and the global variable as well? We test this in the following piece of code: chapter of our course
Deep Copy is available in a
Dictionaries def f(): version for Python
s = "I love London!" 2.x as well: Global
Sets and Frozen print(s)
Sets vs. Local Variables
s = "I love Paris!" and Namespaces in
An Extensive
f() Python 2.x
Example Using
print(s)
Sets
Classroom
input via the The output looks like this: Training
keyboard
I love London! Courses
Conditional
I love Paris!
Statements The goal of this
Loops, while What if we combine the first example with the second one, i.e. we first access s with a print() function, hoping to get the global value, and then assigning a new value to it? Assigning a value to it, means - as we website is to provide
Loop have previously stated - creating a local variable s. So, we would have s both as a global and a local variable in the same scope, i.e. the body of the function. Python fortunately doesn't allow this ambiguity. So, it educational material,
For Loops will throw an error, as we can see in the following example: allowing you to learn
Difference Python on your own.
>>> def f(): Nevertheless, it is
between ... print(s)
interators und faster and more
... s = "I love London!"
efficient to attend a
Iterables ... print(s)
... "real" Python course
Output with Print
>>> s = "I love Paris!" in a classroom, with
Formatted output >>> f() an experienced
with string Traceback (most recent call last): trainer. So why not
modulo and the File "<stdin>", line 1, in <module> attend one of the live
File "<stdin>", line 2, in f Python courses in
format method
UnboundLocalError: local variable 's' referenced before assignment
Functions Strasbourg, Paris,
>>>
Recursion and Luxembourg,
A variable can't be both local and global inside of a function. So Python decides that we want a local variable due to the assignment to s inside of f(), so the first print statement before the definition of s throws the Amsterdam, Zürich /
Recursive
error message above. Any variable which is changed or created inside of a function is local, if it hasn't been declared as a global variable. To tell Python, that we want to use the global variable, we have to explicitly Zurich, Vienna /
Functions
state this by using the keyword "global", as can be seen in the following example: Wien, London, Berlin,
Parameter Munich, Hamburg,
Passing in def f(): Frankfurt or Lake
Functions global s Constance by Bernd
Namespaces print(s) Klein, the author of
s = "Only in spring, but London is great as well!" this tutorial?
Global and Local
print(s)
Variables
Decorators
Memoization with s = "I am looking for a course in Paris!" Onsite Training
Decorators
f() Courses
print(s)
Read and Write
Let us come to your
Files We have solved our problem. There is no ambiguity left. The output of this small script looks like this:
company,
Modular
I am looking for a course in Paris! organization or
Programming institute and train
Only in spring, but London is great as well!
and Modules Only in spring, but London is great as well! your employees, as
Packages in we've done it many
Python Local variables of functions can't be accessed from outside, when the function call has finished: times in Amsterdam
Regular (The Netherlands),
def f(): Berlin (Germany),
Expressions s = "I am globally not known"
Regular Bern (Switzerland),
print(s)
Basel (Switzerland),
Expressions,
f() Zurich (Switzerland),
Advanced
print(s) Locarno
Lambda (Switzerland), Den
Operator, Filter, Starting this script gives us the following output with an error message: Haag (The Hague),
Reduce and Map Hamburg (Germany),
List monty@python:~$ python3 ex.py Frankfurt (Germany),
I am globally not known
Comprehension Toronto (Canada),
Traceback (most recent call last):
Iterators and File "ex.py", line 6, in <module> Edmonton (Canada),
print(s) Munich (Germany)
Generators
NameError: name 's' is not defined and many other
Exception
monty@python:~$ cities. We do training
Handling courses in England,
Tests, DocTests, The following example shows a wild combination of local and global variables and function parameters: Switzerland,
UnitTests Liechtenstein,
Object Oriented Austria, Germany,
def foo(x, y):
Programming France, Belgium, the
global a
Class and a = 42 Netherlands,
Instance x,y = y,x Luxembourg, Poland,
b = 33 UK, Italy and other
Attributes
b = 17 locations in Europe
Properties vs. c = 100 and in Canada.
getters and print(a,b,x,y)
setters This way you will get
a, b, x, y = 1, 15, 3,4
Inheritance a perfect training up
foo(17, 4)
Multiple print(a, b, x, y) to your needs and it
Inheritance will be extremely cost
Magic Methods The output looks like this: efficient as well.
Contact us so we can
and Operator
42 17 4 17 define and find the
Overloading 42 15 3 4 best course
OOP, Inheritance curriculum to meet
Example your needs, and
Slots schedule course
Classes and sessions to be held at
Class Creation Global Variables in Nested Functions your location.
Road to
Metaclasses We will examine now what will happen, if we use the global keyword inside of nested functions. The following example shows a situation where a variable x is used in various scopes:
Metaclasses Skilled Python
def f():
Metaclass Use x = 42
Programmers
Case: Count def g():
Function Calls global x You are looking for
x = 43 experienced Python
Abstract Classes print("Before calling g: " + str(x)) developers or
print("Calling g now:") programmers? We
g()
can help you, please
Global print("After calling g: " + str(x))
contact us.
f()
print("x in main: " + str(x)) Quote of the
The general
Day:
meanings of global: This program returns the following results:
1. involving the
Before calling g: 42 Fools ignore
entire earth; not
Calling g now: complexity.
limited or provincial
After calling g: 42 Pragmatists suffer it.
in scope; as, global
x in main: 43 Some can avoid it.
war; global monetary
Geniuses remove it.
policy.
We can see that the global statement inside of the nested function g does not affect the variable x of the function f, i.e. it keeps its value 42. We can also deduce from this example that after calling f() a variable x (Alan Perlis)
2. shaped like a
exists in the module namespace and has the value 43. This means that the global keyword in nested functions does not affect the namespace of their enclosing namespace! This is consistent to what we have found
globe, sphere or a
out in the previous subchapter: A variable defined inside of a function is local unless it is explicitly marked as global. In other words, we can refer a variable name in any enclosing scope, but we can only rebind
ball, "a spherical
variable names in the local scope by assigning to it or in the module-global scope by using a global declaration. We need a way to access variables of other scopes as well. The way to do this are nonlocal definitions,
object"; spherical.
which we will explain in the next chapter.
3. broad in scope or
content;
nonlocal Variables Data Protection
comprehensive.
Opposite of
Declaration
noncomprehensive. Python3 introduced nonlocal variables as a new kind of variables. nonlocal variables have a lot in common with global variables. One difference to global variables lies in the fact that it is not possible to change
4. (Computers) variables from the module scope, i.e. variables which are not defined inside of a function, by using the nonlocal statement. We show this in the two following examples: Data Protection
Accessible and Declaration
def f():
effective throughout
global x
an entire computer print(x)
program, rather than
in only one x = 3
subroutine; -- used f()
of variables; as,
global variable. This program is correct and returns the number 3 as the output. We will change "global" to "nonlocal" in the following program:
Opposite of local.
def f():
nonlocal x
print(x)
Local
x = 3
f()
Originates from the
latin word "locus"
The program, which we have saved as example1.py, cannot be executed anymore now. We get the following error:
meaning place. It
means pertaining to File "example1.py", line 2
or of a particular nonlocal x
place, or to a definite SyntaxError: no binding for nonlocal 'x' found
region or portion of
space; restricted to This means that nonlocal bindings can only be used inside of nested functions. A nonlocal variable has to be defined in the enclosing function scope. If the variable is not defined in the enclosing function scope, the
one place or region; variable cannot be defined in the nested scope. This is another difference to the "global" semantics.
as, a local custom.
def f():
x = 42
def g():
nonlocal x
This website is x = 43
created by: print("Before calling g: " + str(x))
print("Calling g now:")
g()
print("After calling g: " + str(x))

x = 3
f()
print("x in main: " + str(x))

Calling the previous program results in the following output:

Before calling g: 42
Calling g now:
After calling g: 43
x in main: 3

Python Training In the previous example the variable x was defined prior to the call of g. We get an error if it isn't defined:
Courses in Toronto,
def f():
Canada
#x = 42
On site trainings in def g():
Europe, Canada and nonlocal x
the US. x = 43
print("Before calling g: " + str(x))
print("Calling g now:")
g()
print("After calling g: " + str(x))
Think Globally,
Act Locally x = 3
f()
"Think Globally, Act print("x in main: " + str(x))
Locally" is an urgent
request to people to We get the following error message:
consider the health of File "example3.py", line 4
the entire planet and nonlocal x
to take action in their SyntaxError: no binding for nonlocal 'x' found
own environment,
i.e. local communities The program works find - with or without the line "x = 42" inside of f - , when we change "nonlocal" to "global":
and cities.
def f():
But this principle #x = 42
def g():
should be a guiding
global x
line to programming x = 43
both in Python and print("Before calling g: " + str(x))
and other print("Calling g now:")
programming g()
languages as well. print("After calling g: " + str(x))

x = 3
f()
print("x in main: " + str(x))

This leads to the following output:

Calling g now:
The value of x after the call to g: 43

Before calling g: 3
Calling g now:
After calling g: 43
x in main: 43

Yet there is a huge difference: The value of the global x is changed now!

Previous Chapter: Namespaces


Next Chapter: Decorators

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like