Python variable names [duplicate] - python

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.

Related

Python variable inheritance not working (as expected) [duplicate]

This question already has answers here:
How to create dynamical scoped variables in Python?
(4 answers)
Closed 2 years ago.
Why, in this code, can't I access db or file from inside do_more()?
def do_stuff(queue):
db = getDbConn()
while True:
file = queue.get() #DirEntry object
...
do_more(otherObject)
q.task_done()
I'm aware I could pass db and file as arguments to do_more(), but I feel like those variables should just be available in functions called from other functions. It works that way from main to first level functions. What am I missing here?
In the code you provided, you don't even attempt using the variables from do_stuff.
But as a general rule, you should be able to use variables from a parent function inside a child function, either by passing them as variables or by using them when initializing the child function, like this:
def foo():
foo2 = "foo"
def bar():
print(foo2)
bar()
foo()
If i did not answer your question let me know.
no , you cant access those variables , I know what you think , which is wrong.
you can access variables inside loops and if statements, not here.
imagine you have a function which is used in many different places, in that case you have access from this function to many variables which makes things complicated.
functions should be stand-alone objects which take some arguments do stuff and return something.so inside a function scope you can only see variables which are defined there and the arguments passed from the parent function using parenthesis.

python, stop variable reassignment in every function call? [duplicate]

This question already has answers here:
Keep the lifespan of variable after multiple function calls?
(4 answers)
Closed 5 years ago.
Assuming:
def myfunc(x):
listv = []
listv.append(x)
is there a keyword to stop a variable (listv) from being reassigned?
Let's suppose that NRA is a keyword:
def myfunc(x):
NRA listv = []
listv.append(x)
...line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!
Variables in functions are not supposed to be persistent between function calls. Because functions are meant to be reusable codes that can be called from different context in the program. So to your answer, NO! There's no keyword for making a variable declared in function persistent.

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

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?

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)

Why 4 is returned for the follow code in Python [duplicate]

This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 8 years ago.
>>> a = 10
>>> def f(x):
return x + a
>>> a = 3
>>> f(1)
According to my experience on Java, the definition of f contains a local variable a, but how could the global binding a been visible on the function f call stack environment?
I did a research on the python syntax and found that's true, could anybody offer some background on why python dealing variable scope this way? thanks.
Your function call is in the last line.
When the function gets called, python first looks up for local variables with name a,
if not found, it goes into global scope, and in global scope, the last assigned value of a is 3 ( just before the function was called)
What you may find even stranger is that this will also work:
>>> def f(x):
return x + a
>>> a = 3
>>> f(1)
Note that a hasn't even been defined before the function f. It still works because your call to f is after a is defined and placed in the global namespace. At that point, since f does not have a in its local namespace, it will fetch it from the global namespace.
You can fetch the contents of the global namespace and check for yourself with globals(), and the local namespace with locals(). There's also some neat tricks you can do by manipulating the namespaces directly, but that is in most cases considered bad coding practice in Python, unless you really have a compelling reason and know what you're doing.
It would return 4 because you declare a and f(x) a function then you give valuea=3 and then you give x=1 so the function would return 3+1 which is 4
Python decide variable scope in function based on where they have been assigned. As you didn't assigned variable 'a' inside function so it starts looking out and consider the global value.
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as global.
Ref : http://effbot.org/pyfaq/what-are-the-rules-for-local-and-global-variables-in-python.htm
Java is a purely object-oriented language, while Python is not. Python supports both structural as well as object-oriented paradigms.
Global variables are part of the structural programming paradigm. So global variables will be available in the scope of a function, unless another variable with exactly the same name exists in the local scope of that function.

Categories