Why are objects allowed to be used after a block? [duplicate] - python

This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 5 years ago.
In this code, why do a and b not get destroyed at the ends of their respective blocks?
flag = True
if flag:
a = 1
for i in range(2):
b = 2
print(a, b)
Instead, this code prints 1 2. Why does Python allow this? When can I rely on this behavior?

Read up on the scoping rules for Python. In short, a scope is started with a new module: function, method, class, etc. Mere control flow statements (e.g. if and for) do not start a new scope. The scope of a variable is from its firs definition to the end of that scope.
Since this example has only one scope, each variable is good from its first assignment to the end of the file.
Is that enough to clear up the problem?

Related

is there any alternative in python to replace the variable in runtime like in unix shell script {!variableName} [duplicate]

This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
How do I create variable variables?
(17 answers)
Closed 2 years ago.
In unix shell script:
if I call
function_name "${!variable}" -> variable will replaced during the execution/runtime
is there something alternative exists in python? there are some other logic involved prior creating the variable. But I'm interested in {!variable} alternative.
You are looking for the eval function:
a = "there"
b = "a"
eval(b)
Yielding the output:
'there'
Of course, the eval function, while being a bit more verbose than the bash indirect variable reference, is also much more versatile, as you can have the indirectly referenced variable (b in this case), contain any python expression.
In python functions are 1st class objects. Which means you can pass them around just like any variable.
def print_this():
print('this')
def print_that():
print('that')
p1 = print_this
p2 = print_that
p1()
p2()
So you don't need to use eval.

Why does python let you access loop variables out of scope [duplicate]

This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 3 years ago.
I wrote something like this where I am able to access a variable that is used through pythons in for loop syntax and then being able to access that variable, I was wondering if there is a specific reason to being able to do this
for i in array:
do_something(i)
b = i
From Short description of the scoping rules?: "The for loop does not have its own namespace"
This means that variables declared in the loop are available for the rest of the code in the same scope as the loop itself

Python variable names [duplicate]

This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 4 years ago.
I was surprised today to find out that the following appears to be valid code in Python:
def foo(n):
foo = n * 10
return foo
foo(5)
What in Python allows for a variable name to match the name of the function it is in? Is it just some kind of scoping rule that helps to keep these 2 things separate? so Python simply considers a program's function namespace to be a completely separate animal from the program's variable name space?
(Note: I would hate to do this in my own programs as it's a tad confusing but c'est la vie as they say in France.)
There are two separate scopes at play here: the global namespace, and the local namespace of the function.
foo the function lives in the global namespace, because def foo(n): ... is executed at the top level of the module.
foo the integer is a local variable inside the foo() function. The name only exists while foo() executes. When return foo is executed, the function ends and all local variables are cleaned up.
So yes, here these two can live next to one another perfectly fine.

inner function accessing outer function's variable [duplicate]

This question already has answers here:
Can you explain closures (as they relate to Python)?
(13 answers)
Closed 6 years ago.
Let's suppose to have this simple code:
def my_outer_function():
outer_var = 123
def my_inner_function():
return outer_var + 1
return my_inner_function
get_inner = my_outer_function()
get_inner()
I wonder there isn't any kind of runtime error. outer_var - the variable of the outer function - is available only when that function is running on, i.e. it vanishes when my_outer_function ends. But when I call get_inner(), my_outer_function() is already ended so I would have bet on a runtime error since my_inner_function couldn't find outer_var.
How do you explain all this?
the variable of the outer function is available only when that function is running on, i.e. it vanishes when my_outer_function ends.
That's not entirely true. The variable is available in my_outer_function's scope. my_inner_function has the scope of its own declarations and its parent's scope.
my_inner_function references a variable outside of its own scope, and so those references are bound to my_inner_function as a closure when its parent's scope is no longer available. To learn more about closures, see Can you explain closures (as they relate to Python)? (taken from Paul Rooney's comment)

Do iteration variable exist after the iteration statement in python? [duplicate]

This question already has answers here:
Scoping in Python 'for' loops
(8 answers)
Closed 9 years ago.
I have tried this code :
for i in range(10)
print(line, i)
print(line, i)
and the program executed without error, so why is i declared even after the for statement, it must no longer exist.
Yes, your iteration variable isn’t deleted when the loop is finished. As the documentation puts it: „Names in the target list are not deleted when the loop is finished”.
This has to do with variable scopes. As has been pointed out, the variable i exists within the scope of the function you’re in. A loop does not create an extra scope in python.
The scope is within a function, not a loop. A little different than other programming languages.

Categories