This question already has answers here:
What's the scope of a variable initialized in an if statement?
(7 answers)
Closed 3 years ago.
In Python, are variable scopes inside if-statements visible outside of the if-statement? (coming from a Java background, so find this a bit odd)
In the following case, name is first defined inside the if-block but the variable is visible outside of the if-block as well. I was expecting an error to occur but 'joe' gets printed.
if 1==1:
name = 'joe'
print(name)
if statements don't define a scope in Python.
Neither do loops, with statements, try / except, etc.
Only modules, functions and classes define scopes.
See Python Scopes and Namespaces in the Python Tutorial.
Yes, in Python, variable scopes inside if-statements are visible outside of the if-statement.
Two related questions gave an interestion discussion:
Short Description of the Scoping Rules?
and
Python variable scope error
All python variables used in a function live in the function level scope. (ignoring global and closure variables)
It is useful in case like this:
if foo.contains('bar'):
value = 2 + foo.count('b')
else:
value = 0
That way I don't have to declare the variable before the if statement.
Related
This question already has answers here:
How to get local variables updated, when using the `exec` call?
(3 answers)
Closed 1 year ago.
Given a string (e.g. "lista=[1,2,3]") I would like to be able to use the variable lista.
exec() does the work outside a function, but when used inside a function the variables cannot be used in that same function. I guess it has something to do with local and global variables but I don't really understand the problem.
For example,
def funcion(texto):
exec(texto)
print(lista)
funcion("lista = [3,4,5]")
Gives the error: NameError: name 'lista' is not defined.
add globals
def funcion(texto):
exec(texto, globals())
print(lista)
funcion("lista = [3,4,5]")
This question already has answers here:
How to restore a builtin that I overwrote by accident?
(3 answers)
Closed 2 years ago.
I am new to python, and realized that i can assign print i.e. an inbuilt function as a variable, then when i use print('hello world')this shows the exact error that i faced
I am familiar to c++ and even in that we were never allowed to use an inbuilt function as a variable name.
those were the fundamental rules for naming a variable
If python.org has issued the new version I'm sure they would have done it for a reason, bbut i want to know how do i access my print statement after assigning a value to it?
you won't be able to access your print function unless you do hacky things, which I recommend not to do them in the middle of your code.
Also it is good to know that python (as c++) has scopes for variables, and variables "die" and they are no longer accessible when scope ends. For instance:
def change_print_value():
print = 3
change_print_value()
print('Print works as expected')
It is a good practice to avoid using reserved keywords as variable names. Any IDE has the keywords highlighted, so you can easily realize when you are using a keyword where you shouldn't.
print is not part of the reserved keywords list in python. Here's a comprehensive list of reserved words.
Functions are first class objects in python, so that means they can be treated and manipulated as objects. Since print is a function (and an object), when you call print = 1, you reassign the variable print to have a value of 1, so the functionality "disappears".
This question already has answers here:
Scope of variable within "with" statement?
(2 answers)
Closed 3 years ago.
I didn't find the answer for this question on stackoverflow, so I thought it might be helpful to ask it, and have it here -
I am declaring a new dictionary after I open a file, in the following way -
with open('some_file.txt','r') as f:
dict = json.loads(f.read()) #converts text to a dictionary
my question is - will I be able to reach dict content's even after the 'with' scope ends.
Thanks
Yes, in Python the scope of a variable ends only when the code block it's defined in ends, and the with statement is not a code block per the documentation:
The following are blocks: a module, a function body, and a class
definition. Each command typed interactively is a block. A script file
(a file given as standard input to the interpreter or specified as a
command line argument to the interpreter) is a code block. A script
command (a command specified on the interpreter command line with the
‘-c’ option) is a code block. The string argument passed to the
built-in functions eval() and exec() is a code block.
In python scope is defined by functions. There is no indentation scope (similar to "bracket" scope in other languages). The with part affects just the f object.
Yes you will, you will not be able to access f, everything else is fair game.
This question already has answers here:
How can a name be "unbound" in Python? What code can cause an `UnboundLocalError`?
(3 answers)
Closed 15 days ago.
I am trying to use an if statement to check whether a variable has been assigned and is not None.
# Code that may or may not assign value to 'variable'
if variable:
do things
This throws an error at the line with the if statement: "UnboundLocalError: local variable 'variable' referenced before assignment".
I thought if the variable wasn't assigned it would just be interpreted as False?
I've tried if variable in locals(): to no avail.
What's going on? What can I do to achieve the result I'm looking for?
Thanks
It's better to simply initialize x to None at the beginning and test for None (as in Ned's answer).
What's going on is that whenever you reference a variable on a "load" (i.e. rvalue), Python looks it up and requires it to exist.
If your variable is named x, the following throws:
if x in locals(): ...
And is not what you wanted, since it would have checked if the value that the variable holds is in locals(). Not whether the name x is there.
But you can do
if 'x' in locals(): ...
At the beginning of the function initialize the variable to None. Then later you can check it with:
if x is not None:
Your assumption was wrong. There is no such thing as a uninitialized variable in Python. Any reference to a "variable" in Python either finds an entry in the namespace of some scope (Local, Enclosing, Global, or Builtin) or it's name lookup error.
It is better to think of Python statements of the form x=y as binding statements rather than assignments. A binding associates a name with an object. The object exists independently of its bindings (instantiated by a literal expression, for example). By contrast, most of the programming languages people are more familiar with have variables ... which have an associated type and location. Python "variables" are entries in a dictionary and the id() returns the the location of the object to which a name is bound. (The fact that this is a memory location is an implementation detail; but the principle is that Python "variable names" are not like the "variables" of more conventional languages).
Here's a bit more on that: https://softwareengineering.stackexchange.com/a/200123/11737
The best way to do accomplish this is simply refrain from using names before binding values thereto. Poking around in locals() or globals() for such things is just poor, ugly, coding practice.
This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 5 years ago.
I was thinking that variable can be only accessed after its declaration.
But apparently, Python's name resolution starts to look for from inside to outer.
My question is that this is bad practice in terms of readability? I was wondering that this might be a common knowledge for Pythonista so that I can write this kind of code from now on.
def outer():
def inner():
print x
x = ‘foo’
inner()
>>> outer()
>>> ‘foo’
When you invoke inner(), it starts executing. On line print x it sees variable name x. Then it looks to inner scope of function inner, doesn't find variable x there. Then it looks to the outer scope, namely, scope of outer. At this moment there is already variable x defined (as it is done before inner() invokation) and this variable is used.