What's the scope of a variable initialized in an if statement? - python

This could be a simple scoping question. The following code in a Python file (module) is confusing me slightly:
if __name__ == '__main__':
x = 1
print x
In other languages I've worked in, this code would throw an exception, as the x variable is local to the if statement and should not exist outside of it. But this code executes, and prints 1. Can anyone explain this behavior? Are all variables created in a module global/available to the entire module?

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.
(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)

Yes, they're in the same "local scope", and actually code like this is common in Python:
if condition:
x = 'something'
else:
x = 'something else'
use(x)
Note that x isn't declared or initialized before the condition, like it would be in C or Java, for example.
In other words, Python does not have block-level scopes. Be careful, though, with examples such as
if False:
x = 3
print(x)
which would clearly raise a NameError exception.

Scope in python follows this order:
Search the local scope
Search the scope of any enclosing functions
Search the global scope
Search the built-ins
(source)
Notice that if and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.

As Eli said, Python doesn't require variable declaration. In C you would say:
int x;
if(something)
x = 1;
else
x = 2;
but in Python declaration is implicit, so when you assign to x it is automatically declared. It's because Python is dynamically typed - it wouldn't work in a statically typed language, because depending on the path used, a variable might be used without being declared. This would be caught at compile time in a statically typed language, but with a dynamically typed language it's allowed.
The only reason that a statically typed language is limited to having to declare variables outside of if statements in because of this problem. Embrace the dynamic!

Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost "block". It is as though you declared int x at the top of the function (or class, or module), except that in Python you don't have to declare variables.
Note that the existence of the variable x is checked only at runtime -- that is, when you get to the print x statement. If __name__ didn't equal "__main__" then you would get an exception: NameError: name 'x' is not defined.

Yes. It is also true for for scope. But not functions of course.
In your example: if the condition in the if statement is false, x will not be defined though.

you're executing this code from command line therefore if conditions is true and x is set. Compare:
>>> if False:
y = 42
>>> y
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
y
NameError: name 'y' is not defined

Related

Why Python "global" statement is always evaluated, even under conditional statement that is not met?

I don't know how to explain the case, just try for yourself:
x = 7
def f():
if False:
global x
print("global")
x += 1
f()
print(x)
In my opinion, the above code should result in "UnboundLocalError: local variable 'x' referenced before assignment", but instead it not only works, but it changes the global variable 'x'.
A function gets a local namespace every time it is called. Python needs a way to know which variables are defined in that namespace or a containing namespace. Instead of requiring that all local variables be declared local, python's rule is that any variable that is assigned in a function is local to that function. It figures this out at compile time.
The global keyword does the opposite. It tells python that in this single function, assignment to the "global" variable is really an assignment in the enclosing namespace. Like local variables, this is figured out when the function is compiled. Because of compilation issues, python requires that the global be declared before the first reference to the variable. This is a compile thing, not a runtime thing, so its okay for it to be in a block that isn't ever really run.

If python interpreter immediately halts execution when error is encountered, then how 2 different error messages are generated? [duplicate]

When I try this code:
a, b, c = (1, 2, 3)
def test():
print(a)
print(b)
print(c)
c += 1
test()
I get an error from the print(c) line that says:
UnboundLocalError: local variable 'c' referenced before assignment
in newer versions of Python, or
UnboundLocalError: 'c' not assigned
in some older versions.
If I comment out c += 1, both prints are successful.
I don't understand: why does printing a and b work, if c does not? How did c += 1 cause print(c) to fail, even when it comes later in the code?
It seems like the assignment c += 1 creates a local variable c, which takes precedence over the global c. But how can a variable "steal" scope before it exists? Why is c apparently local here?
See also Using global variables in a function for questions that are simply about how to reassign a global variable from within a function, and Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope? for reassigning from an enclosing function (closure).
See Why isn't the 'global' keyword needed to access a global variable? for cases where OP expected an error but didn't get one, from simply accessing a global without the global keyword.
See How can a name be "unbound" in Python? What code can cause an `UnboundLocalError`? for cases where OP expected the variable to be local, but has a logical error that prevents assignment in every case.
Python treats variables in functions differently depending on whether you assign values to them from inside or outside the function. If a variable is assigned within a function, it is treated by default as a local variable. Therefore, when you uncomment the line, you are trying to reference the local variable c before any value has been assigned to it.
If you want the variable c to refer to the global c = 3 assigned before the function, put
global c
as the first line of the function.
As for python 3, there is now
nonlocal c
that you can use to refer to the nearest enclosing function scope that has a c variable.
Python is a little weird in that it keeps everything in a dictionary for the various scopes. The original a,b,c are in the uppermost scope and so in that uppermost dictionary. The function has its own dictionary. When you reach the print(a) and print(b) statements, there's nothing by that name in the dictionary, so Python looks up the list and finds them in the global dictionary.
Now we get to c+=1, which is, of course, equivalent to c=c+1. When Python scans that line, it says "aha, there's a variable named c, I'll put it into my local scope dictionary." Then when it goes looking for a value for c for the c on the right hand side of the assignment, it finds its local variable named c, which has no value yet, and so throws the error.
The statement global c mentioned above simply tells the parser that it uses the c from the global scope and so doesn't need a new one.
The reason it says there's an issue on the line it does is because it is effectively looking for the names before it tries to generate code, and so in some sense doesn't think it's really doing that line yet. I'd argue that is a usability bug, but it's generally a good practice to just learn not to take a compiler's messages too seriously.
If it's any comfort, I spent probably a day digging and experimenting with this same issue before I found something Guido had written about the dictionaries that Explained Everything.
Update, see comments:
It doesn't scan the code twice, but it does scan the code in two phases, lexing and parsing.
Consider how the parse of this line of code works. The lexer reads the source text and breaks it into lexemes, the "smallest components" of the grammar. So when it hits the line
c+=1
it breaks it up into something like
SYMBOL(c) OPERATOR(+=) DIGIT(1)
The parser eventually wants to make this into a parse tree and execute it, but since it's an assignment, before it does, it looks for the name c in the local dictionary, doesn't see it, and inserts it in the dictionary, marking it as uninitialized. In a fully compiled language, it would just go into the symbol table and wait for the parse, but since it WON'T have the luxury of a second pass, the lexer does a little extra work to make life easier later on. Only, then it sees the OPERATOR, sees that the rules say "if you have an operator += the left hand side must have been initialized" and says "whoops!"
The point here is that it hasn't really started the parse of the line yet. This is all happening sort of preparatory to the actual parse, so the line counter hasn't advanced to the next line. Thus when it signals the error, it still thinks its on the previous line.
As I say, you could argue it's a usability bug, but its actually a fairly common thing. Some compilers are more honest about it and say "error on or around line XXX", but this one doesn't.
Taking a look at the disassembly may clarify what is happening:
>>> def f():
... print a
... print b
... a = 1
>>> import dis
>>> dis.dis(f)
2 0 LOAD_FAST 0 (a)
3 PRINT_ITEM
4 PRINT_NEWLINE
3 5 LOAD_GLOBAL 0 (b)
8 PRINT_ITEM
9 PRINT_NEWLINE
4 10 LOAD_CONST 1 (1)
13 STORE_FAST 0 (a)
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
As you can see, the bytecode for accessing a is LOAD_FAST, and for b, LOAD_GLOBAL. This is because the compiler has identified that a is assigned to within the function, and classified it as a local variable. The access mechanism for locals is fundamentally different for globals - they are statically assigned an offset in the frame's variables table, meaning lookup is a quick index, rather than the more expensive dict lookup as for globals. Because of this, Python is reading the print a line as "get the value of local variable 'a' held in slot 0, and print it", and when it detects that this variable is still uninitialised, raises an exception.
Python has rather interesting behavior when you try traditional global variable semantics. I don't remember the details, but you can read the value of a variable declared in 'global' scope just fine, but if you want to modify it, you have to use the global keyword. Try changing test() to this:
def test():
global c
print(a)
print(b)
print(c) # (A)
c+=1 # (B)
Also, the reason you are getting this error is because you can also declare a new variable inside that function with the same name as a 'global' one, and it would be completely separate. The interpreter thinks you are trying to make a new variable in this scope called c and modify it all in one operation, which isn't allowed in Python because this new c wasn't initialized.
The best example that makes it clear is:
bar = 42
def foo():
print bar
if False:
bar = 0
when calling foo() , this also raises UnboundLocalError although we will never reach to line bar=0, so logically local variable should never be created.
The mystery lies in "Python is an Interpreted Language" and the declaration of the function foo is interpreted as a single statement (i.e. a compound statement), it just interprets it dumbly and creates local and global scopes. So bar is recognized in local scope before execution.
For more examples like this Read this post: http://blog.amir.rachum.com/blog/2013/07/09/python-common-newbie-mistakes-part-2/
This post provides a Complete Description and Analyses of the Python Scoping of variables:
Here are two links that may help
1: docs.python.org/3.1/faq/programming.html?highlight=nonlocal#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
2: docs.python.org/3.1/faq/programming.html?highlight=nonlocal#how-do-i-write-a-function-with-output-parameters-call-by-reference
link one describes the error UnboundLocalError. Link two can help with with re-writing your test function. Based on link two, the original problem could be rewritten as:
>>> a, b, c = (1, 2, 3)
>>> print (a, b, c)
(1, 2, 3)
>>> def test (a, b, c):
... print (a)
... print (b)
... print (c)
... c += 1
... return a, b, c
...
>>> a, b, c = test (a, b, c)
1
2
3
>>> print (a, b ,c)
(1, 2, 4)
The Python interpreter will read a function as a complete unit. I think of it as reading it in two passes, once to gather its closure (the local variables), then again to turn it into byte-code.
As I'm sure you were already aware, any name used on the left of a '=' is implicitly a local variable. More than once I've been caught out by changing a variable access to a += and it's suddenly a different variable.
I also wanted to point out it's not really anything to do with global scope specifically. You get the same behaviour with nested functions.
c+=1 assigns c, python assumes assigned variables are local, but in this case it hasn't been declared locally.
Either use the global or nonlocal keywords.
nonlocal works only in python 3, so if you're using python 2 and don't want to make your variable global, you can use a mutable object:
my_variables = { # a mutable object
'c': 3
}
def test():
my_variables['c'] +=1
test()
This is not a direct answer to your question, but it is closely related, as it's another gotcha caused by the relationship between augmented assignment and function scopes.
In most cases, you tend to think of augmented assignment (a += b) as exactly equivalent to simple assignment (a = a + b). It is possible to get into some trouble with this though, in one corner case. Let me explain:
The way Python's simple assignment works means that if a is passed into a function (like func(a); note that Python is always pass-by-reference), then a = a + b will not modify the a that is passed in. Instead, it will just modify the local pointer to a.
But if you use a += b, then it is sometimes implemented as:
a = a + b
or sometimes (if the method exists) as:
a.__iadd__(b)
In the first case (as long as a is not declared global), there are no side-effects outside local scope, as the assignment to a is just a pointer update.
In the second case, a will actually modify itself, so all references to a will point to the modified version. This is demonstrated by the following code:
def copy_on_write(a):
a = a + a
def inplace_add(a):
a += a
a = [1]
copy_on_write(a)
print a # [1]
inplace_add(a)
print a # [1, 1]
b = 1
copy_on_write(b)
print b # [1]
inplace_add(b)
print b # 1
So the trick is to avoid augmented assignment on function arguments (I try to only use it for local/loop variables). Use simple assignment, and you will be safe from ambiguous behaviour.
Summary
Python decides the scope of the variable ahead of time. Unless explicitly overridden using the global or nonlocal (in 3.x) keywords, variables will be recognized as local based on the existence of any operation that would change the binding of a name. That includes ordinary assignments, augmented assignments like +=, various less obvious forms of assignment (the for construct, nested functions and classes, import statements...) as well as unbinding (using del). The actual execution of such code is irrelevant.
This is also explained in the documentation.
Discussion
Contrary to popular belief, Python is not an "interpreted" language in any meaningful sense. (Those are vanishingly rare now.) The reference implementation of Python compiles Python code in much the same way as Java or C#: it is translated into opcodes ("bytecode") for a virtual machine, which is then emulated. Other implementations must also compile the code; otherwise, eval and exec could not properly return an object, and SyntaxErrors could not be detected without actually running the code.
How Python determines variable scope
During compilation (whether on the reference implementation or not), Python follows simple rules for decisions about variable scope in a function:
If the function contains a global or nonlocal declaration for a name, that name is treated as referring to the global scope or the first enclosing scope that contains the name, respectively.
Otherwise, if it contains any syntax for changing the binding (either assignment or deletion) of the name, even if the code would not actually change the binding at runtime, the name is local.
Otherwise, it refers to either the first enclosing scope that contains the name, or the global scope otherwise.
Importantly, the scope is resolved at compile time. The generated bytecode will directly indicate where to look. In CPython 3.8 for example, there are separate opcodes LOAD_CONST (constants known at compile time), LOAD_FAST (locals), LOAD_DEREF (implement nonlocal lookup by looking in a closure, which is implemented as a tuple of "cell" objects), LOAD_CLOSURE (look for a local variable in the closure object that was created for a nested function), and LOAD_GLOBAL (look something up in either the global namespace or the builtin namespace).
There is no "default" value for these names. If they haven't been assigned before they're looked up, a NameError occurs. Specifically, for local lookups, UnboundLocalError occurs; this is a subtype of NameError.
Special (and not-special) cases
There are some important considerations here, keeping in mind that the syntax rule is implemented at compile time, with no static analysis:
It does not matter if the global variable is a builtin function etc., rather than an explicitly created global:
def x():
int = int('1') # `int` is local!
(Of course, it is a bad idea to shadow builtin names like this anyway, and global cannot help (just like using the same code outside of a function will still cause problems). See https://stackoverflow.com/questions/6039605.)
It does not matter if the code could never be reached:
y = 1
def x():
return y # local!
if False:
y = 0
It does not matter if the assignment would be optimized into an in-place modification (e.g. extending a list) - conceptually, the value is still assigned, and this is reflected in the bytecode in the reference implementation as a useless reassignment of the name to the same object:
y = []
def x():
y += [1] # local, even though it would modify `y` in-place with `global`
However, it does matter if we do an indexed/slice assignment instead. (This is transformed into a different opcode at compile time, which will in turn call __setitem__.)
y = [0]
def x():
print(y) # global now! No error occurs.
y[0] = 1
There are other forms of assignment, e.g. for loops and imports:
import sys
y = 1
def x():
return y # local!
for y in []:
pass
def z():
print(sys.path) # `sys` is local!
import sys
Another common way to cause problems with import is trying to reuse the module name as a local variable, like so:
import random
def x():
random = random.choice(['heads', 'tails'])
Again, import is assignment, so there is a global variable random. But this global variable is not special; it can just as easily be shadowed by the local random.
Deletion is also changing the name binding, e.g.:
y = 1
def x():
return y # local!
del y
The interested reader, using the reference implementation, is encouraged to inspect each of these examples using the dis standard library module.
Enclosing scopes and the nonlocal keyword (in 3.x)
The problem works the same way, mutatis mutandis, for both global and nonlocal keywords. (Python 2.x does not have nonlocal.) Either way, the keyword is necessary to assign to the variable from the outer scope, but is not necessary to merely look it up, nor to mutate the looked-up object. (Again: += on a list mutates the list, but then also reassigns the name to the same list.)
Special note about globals and builtins
As seen above, Python does not treat any names as being "in builtin scope". Instead, the builtins are a fallback used by global-scope lookups. Assigning to these variables will only ever update the global scope, not the builtin scope. However, in the reference implementation, the builtin scope can be modified: it's represented by a variable in the global namespace named __builtins__, which holds a module object (the builtins are implemented in C, but made available as a standard library module called builtins, which is pre-imported and assigned to that global name). Curiously, unlike many other built-in objects, this module object can have its attributes modified and deld. (All of this is, to my understanding, supposed to be considered an unreliable implementation detail; but it has worked this way for quite some time now.)
The best way to reach class variable is directly accesing by class name
class Employee:
counter=0
def __init__(self):
Employee.counter+=1
This issue can also occur when the del keyword is utilized on the variable down the line, after initialization, typically in a loop or a conditional block.
In this case of n = num below, n is a local variable and num is a global variable:
num = 10
def test():
# ↓ Local variable
n = num
# ↑ Global variable
print(n)
test()
So, there is no error:
10
But in this case of num = num below, num on the both side are local variables and num on the right side is not defined yet:
num = 10
def test():
# ↓ Local variable
num = num
# ↑ Local variable not defined yet
print(num)
test()
So, there is the error below:
UnboundLocalError: local variable 'num' referenced before assignment
In addition, even if removing num = 10 as shown below:
# num = 10 # Removed
def test():
# ↓ Local variable
num = num
# ↑ Local variable not defined yet
print(num)
test()
There is the same error below:
UnboundLocalError: local variable 'num' referenced before assignment
So to solve the error above, put global num before num = num as shown below:
num = 10
def test():
global num # Here
num = num
print(num)
test()
Then, the error above is solved as shown below:
10
Or, define the local variable num = 5 before num = num as shown below:
num = 10
def test():
num = 5 # Here
num = num
print(num)
test()
Then, the error above is solved as shown below:
5
You can also get this message if you define a variable with the same name as a method.
For example:
def teams():
...
def some_other_method():
teams = teams()
The solution, is to rename method teams() to something else like get_teams().
Since it is only used locally, the Python message is rather misleading!
You end up with something like this to get around it:
def get_teams():
...
def some_other_method():
teams = get_teams()

Why does writing to a variable change its scope?

Take the following code sample
var = True
def func1():
if var:
print("True")
else:
print("False")
# var = True
func1()
This prints True as one would expect.
However, if I uncomment # var = True, I get the error
UnboundLocalError: local variable 'var' referenced before assignment
Why does writing to a variable make an otherwise accessible variable inaccessible? What was the rationale behind this design choice?
Note I know how to solve it (with the global keyword). My question is why was it decided to behave this way.
Because:
Namespaces exist: the same variable name can be used at module level and inside functions, and have nothing to do with each other.
Python does not require variables to be declared, for ease of use
There still needs to be a way to distinguish between local and global variables
In cases where there is likely unexpected behavior, it is better to throw an error than to silently accept it
So Python chose the rule "if a variable name is assigned to within a function, then that name refers to a local variable" (because if it's never assigned to, it clearly isn't local as it never gets a value).
Your code could have been interpreted as using the module-level variable first (in the if: line), and then using the local variable later for the assignment. But, that will very often not be the expected behavior. So Guido decided that Python would not work like that, and throw the error instead.
Python defaults to implicit variable declaration via assignment, in order to remove the need for additional explicit declarations. Just "implicit declaration" leaves several options what assignment in nested scopes means, most prominently:
Assignment always declares a variable in the inner-most scope.
Assignment always declares a variable in the outer-most scope.
Assignment declares a variable in the inner-most scope, unless declared in any outer scope.
Assignment declares a variable in the inner-most scope, readable only after assignment.
The latter two options mean that a variable does not have a scope well-defined just by the assignment itself. They are "declaration via assignment + X" which can lead to unintended interactions between unrelated code.
That leaves the decision of whether "writing to a variable" should preferably happen to isolated local or shared global variables.
The Python designers consider it more important to explicitly mark writing to a global variable.
Python FAQ: Why am I getting an UnboundLocalError when the variable has a value?
[...]
This explicit declaration is required in order to remind you that (...) you are actually modifying the value of the variable in the outer scope
This is an intentional asymmetry towards purely reading globals, which is considered proper practice.
Python FAQ: What are the rules for local and global variables in Python?
[...]
On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time.
This is described in section 4.2.2 Resolution of names
When a name is not found at all, a NameError exception is raised. If the current scope is a function scope, and the name refers to a local variable that has not yet been bound to a value at the point where the name is used, an UnboundLocalError exception is raised. UnboundLocalError is a subclass of NameError.
If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations.
If a variable name defined in the outer scope is used in a nested scope, it depends on what you do with it in this nested scope:
If you only read a variable, it is the same variable.
If you write to a variable, then Python automatically creates a new, local variable, different from the one in the outer scope.
This local variable prevents access to a variable with the same name in the outer scope.
So writing to a variable don't change its scope, it creates a different, local variable.
You are not able to read this local variable before assigning to it.

Python life variables in if statement [duplicate]

This question already has answers here:
What's the scope of a variable initialized in an if statement?
(7 answers)
Closed 3 years ago.
Can someone tell me where I can find some information about the life of variables in if statement?
In this code:
if 2 < 3:
a = 3
else:
b = 1
print(a)
It prints the variable a. But it seems to me a local variable of the if statement. In C infacts it gives me an error if I create the a variable in the if statement.
I think that this behaviour is because Python is an interpreted language. Am I right?
Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module. However Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.
Taking into consideration your example:
if 2 < 3:
a = 3
else:
b = 1
print(a)
Note that a isn't declared or initialized before the condition unlike C or Java, In other words, Python does not have block-level scopes. You can get more information about it here
Interpretation and compilation have nothing to do with it, and being interpreted is not a property of languages but of implementations.
You could compile Python and interpret C and get exactly the same result.
In Python, you don't need to declare variables and assigning to a variable that doesn't exist creates it.
With a different condition – if 3 < 2:, for instance – your Python code produces an error.
An if statement does not define a scope as it is not a class, module or a function --the only structures in Python that define a scope. Python Scopes and Namespaces
So a variable defined in an if statement is in the tightest outer scope of that if.
See:
What's the scope of a variable initialized in an if statement?
Python variables are scoped to the innermost function, class, or
module in which they're assigned. Control blocks like if and while
blocks don't count, so a variable assigned inside an if is still
scoped to a function, class, or module.
This also applies to for loops which is completely unlike C/C++; a variable created inside the for loop will also be visible to the enclosing function/class/module. Even more curiously, this doesn't apply to variables created inside list comprehensions, which are like self-contained functions, i.e.:
mylist = [zed for zed in range(10)]
In this case, zed is not visible to the enclosing scope! It's all consistent, just a bit different from some other languages. Designer's choice, I guess.
The way c language and its compiler is written is that during compile time itself "declaration of certain identifiers are caught", i.e this kind of grammar is not allowed. you can call it a feature/limitation.
Python - https://www.python.org/dev/peps/pep-0330/
The Python Virtual Machine executes Python programs that have been compiled from the Python language into a bytecode representation.
However, python(is compiled and interpreted, not just interpreted) is flexible i.e you can create and assign values to variables and access them globally, locally and nonlocally(https://docs.python.org/3/reference/simple_stmts.html#grammar-token-nonlocal-stmt), there are many verities you can cook up during your program creation and the compiler allows it as this is the feature of the language itself.
coming to scope and life of variables , see the following description, it might be helpful
When you define a variable at the beginning of your program, it will be a global variable. This means it is accessible from anywhere in your script, including from within a function.
example:-
Program#1
a=1
if2<3
print a
this prints a declared outside.
however, in the below example a is defined globally as 5, but it's defined again as 3, within a function. If you print the value of a from within the function, the value that was defined locally will be printed. If you print a outside of the function, its globally defined value will be printed. The a defined in function() is literally sealed off from the outside world. It can only be accessed locally, from within the same function. So the two a's are different, depending on where you access them from.
Program#2
a = 1
def random1():
a = 3
print(a)
function()
print(a)
Here, you see 3 and 5 as output.
**The scope of a variable refers to the places that you can see or access a variable.
CASE 1:If you define a variable at the top level of your script or module or notebook, this is a global variable:**
>>> global_var = 3
>>> def my_first_func():
... # my_func can 'see' the global variable
... print('I see "global_var" = ', global_var, ' from "my_first_func"')
output:
my_first_func()
I see "global_var" = 3 from "my_first_func"
CASE 2:Variables defined inside a function or class, are not global. Only the function or class can see the variable:
>>> def my_second_func():
... local_var = 10
... print('I see "local_var" = ', local_var, 'from "my_second_func"')
Output:
my_second_func()
I see "local_var" = 10 from "my_second_func"
CASE 3:But here, down in the top (global) level of the notebook, we can’t see that local variable:
Output:
>>> local_var
Traceback (most recent call last):
...
NameError: name 'local_var' is not defined

Local and global references with UnboundLocalError

I don't quite understand why the code
def f():
print(s)
s = "foo"
f()
runs perfectly fine but
def f():
print(s)
s = "bar"
s = "foo"
f()
gives me UnboundLocalError. I know that I can fix this by declaring s as a global variable inside the function or by simply passing s an an argument into the function.
Still I don't understand how python seemingly knows whether or not s is referenced inside the function before the line has been executed? Does python make some sort of list of all local variable references when the function is read into the global frame?
Other answers have focused on the practical aspects of this but have not actually answered the question you asked.
Yes, the Python compiler tracks which variables are assigned when it is compiling a code block (such as in a def). If a name is assigned to in a block, the compiler marks it as local.Take a look at function.__code__.co_varnames to see which variables the compiler has identified.
The nonlocal and global statements can override this.
Yes, Python will look-ahead to recover all variables declared in the local scope. These will then overshadow global variables.
So in your code:
def f():
print(s)
s = "foo"
f()
Python did not find s in the local scope, so it tries to recover it from the global scope and finds "foo".
Now in the other case the following happens:
def f():
print(s)
s = "bar
s = "foo"
f()
Python knows that s is a local variable because it did a look-ahead before runtime, but at runtime it was not assigned yet so it raised and exception.
Note that Python will even let you reference variables that have not been declared anywhere. If you do:
def foo():
return x
f()
You will get a NameError, because Python, when not finding, x as a local variable will just remember that at runtime it should look for a global variable named x and then fail if it does not exist.
So UnboundLocalError means that the variable may eventually be declared in scope but has not been yet. On the other hand NameError means that the variable will never be declared in the local scope, so Python tried to find it in the global scope, but it did not exist.

Categories

Resources