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.
Related
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:
How do I forward-declare a function to avoid `NameError`s for functions defined later?
(17 answers)
Closed 3 years ago.
Simple python script is giving error, what is wrong?
var ="first variable"
myfun(var)
def myfun(var):
print(var)
Error -> NameError: name 'myfun' is not defined
This thing is quite obvious though. Python reads the code line by line and not like C.
Just switch your two blocks i.e. definition of function and calling it.
var ="first variable"
def myfun(var):
print(var)
myfun(var)
This should be good to go.
When python interpreter sees the statement myfun(var), the name myfun is not defined yet. You need to move this line after your function definition.
As the question asks, why doesn't the below code work:
while True:
exec("break")
I am executing the above in pycharm via python 3.5.2 console.
I initially thought it was a context issue but after reading the documentation, I haven't come closer to understanding why this error ocurs.
SyntaxError: 'break' outside loop
Thanks in advance :)
EDIT: I understand that it works without exec() by the way, I'm curious why it won't work with exec (as my circumstances required it) - comprehensive answers welcome.
This is because exec() is ignorant to your surrounding while loop. So the only statement that exec() sees in your example is break. Instead of using exec("break"), simply use break as is.
The only access the exec() function has to its surrounding scope, is the globals() and locals() dictionaries. The documentation for exec() provides some insight into how exec() works:
This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1] If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). Be aware that the return and yield statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.
In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.
If the globals dictionary does not contain a value for the key builtins, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own builtins dictionary into globals before passing it to exec().
The exec statement runs a bit of code independently from the rest of your code.
Hence, the line:
exec("break")
is tantamount to calling break out of nowhere, in a script where nothing else happens, and where no loop exists.
The right way to call the break statement is:
while True:
break
EDIT
The comment from Leaf made me think about it.
Actually, the exec statement does not run the code out of nowhere.
>>> i = 12
>>> exec("print(i)")
12
A better answer, as far as I understand, is that exec runs a piece of code in the same environment as the original code, but independently from it.
This basically means that all the variables that exist at the moment exec is called can be used in the code called by exec. But the context is all new, so return, break, continue and other statements that need a context, will not work, unless the right context is created.
By the way, I kept the word "statement" when talking about exec, but it has become a function in Python3, the same way print did.
exec() is a function. Assuming for simplicity that a function call constitutes a statement of its own (just like in your example), it may end in one of the following ways:
the function returns normally - in this case the next statement according to the control flow is executed;
an exception is raised/thrown from the function - in this case the matching except clause on the call stack (if any) is executed
the entire program is terminated due to an explicit call to exit() or equivalent - there is nothing to execute.
Calling a break (as well as return or yield) from inside exec() would modify the program execution flow in a way that is incompatible with the described aspect of the function call semantics.
Note that the documentation on exec() contains a special note on the use of return and yield inside exec():
Be aware that the return and yield statements may not be used outside
of function definitions even within the context of code passed to the
exec() function.
A similar restriction applies to the break statement (with the difference that it may not be used outside loops), and I wonder why it was not included in the documentation.
exec is a built in function ,
Python insists that break should happen inside the loop,not inside a function
What is happening in your code is you are putting break inside a function which is exec you can't break out of a loop by executing a
break within a function that's called inside the loop.
For Ex
>>> def func():
break
SyntaxError: 'break' outside loop
>>>
Try break without exec():
while True:
break
exec function runs code inside a code and that means it runs out of nowhere! So, your while loop doesn't catch it. Your file is <stdin>. exec runs on another file called <string>. it doesn't recognize it where are you trying to break a loop where there is not a loop. So, your code is this:
while True:
exec("break")
It should be like this:
while True:
break
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.
This question already has answers here:
Why doesn't exec work in a function with a subfunction?
(6 answers)
Closed 7 years ago.
I'm trying to make a "compiler" for my game (so that people could do intresting stuff but not inject code), for mainly declaritive "code" (It would look like this: {"player_location":"IceHall.A7", "print", "You are teleported somewhere", "tiles":{"FirePlace.B3":{'Type':"Corner", "Actions+":{....}}}}. This is how a action is represented; It is called when the player does it.
Anyways, it would have to be compiled into a function. When I tryed out something similar in the interactive interpreter (specifically:
def compile(code):
def act():
exec code
return act
). This (which is would be more or less what would be in the final, with the exception of "code" being constructed by me) raised a odd error:
File "", line 3 SyntaxError:
unqualified exec is not allowed in
function 'act' it is a nested
function.
How do I get around this?
The answer, as said in this question, is the lack of context. I wanted exec code in locals(), globals()