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

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.

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.

How do you assign local variables within a function using exec? [duplicate]

This question already has answers here:
How to get local variables updated, when using the `exec` call?
(3 answers)
Setting variables with exec inside a function
(2 answers)
Closed 3 years ago.
I have a function with an unspecified number of input strings which are intended to be variable names. For example
def f(*args):
for arg in args:
exec('{} = 1'.format(arg))
return a
f('a', 'b')
When running the code, I recieve the following error
NameError: name 'a' is not defined
How do I assign local variables for the function which are to be manipulated or returned? The solution provided in this similar but different question requires creating the variables outside the function, i.e. adding them to the global namespace, but that is not what I want.

How to assign a variable inside a function with the variable as an input for the function? [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 3 years ago.
def convert(target):
#Some code here
target = 20
convert(x)
print(x)
I expected the output to be 20, but there is always an error. "NameError: Name x is not defined" Is there some way that I could fix that?
It sounds like you are trying to pass the value by reference, which goes against the grain of Python, which passes variable by assignment. The easiest "solution" is to refactor your code so it returns the new value, as others have suggested.
In some languages (e.g. PHP), you can specify that certain arguments are to be passed by reference (e.g. by prefixing the variable name with a "&"), but in practice this often makes the code harder to read and debug.
For more information, see:
How do I pass a variable by reference?

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?

Python scope, dictionary and variables difference? [duplicate]

This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Why isn't the 'global' keyword needed to access a global variable?
(11 answers)
Closed 6 months ago.
Python scope
I have the same question but slightly different.
number = 0
def incrementNumber():
number += 1
This one above does not work but this one below does why? Both are outside the function scope.
number = {'num':0}
def incrementNumber():
number['num'] += 1
First one works if I add the variable as global
number = 0
def incrementNumber():
global number
number += 1
Check out this blog post, it's similar to what you're doing. Specifically adam's comment.
You don't assign to dictionaryVar, you assign to dictionaryVar['A'].
So it's never being assigned to, so it's implicitly global. If you
were to actually assign to dictionaryVar, you'd get the behavior you
were "expecting".
In the first case int is not mutable, so when you do number +=1 your are really updating where number points. As you, in general, do not want changes to propagate up-scope with out
explicitly telling it to, python does a copy-on-write and gives you a local variable number. You than increment that variable and it is thrown away when the function returns
In the case of dictionaries, which are mutable, you are grabbing the up-scope reference and then mutating the underlying object, thus your addition propagates out of the function.
In the last case you have explicitly told python to not make number a local variable, thus the changes propagate out as you want.
related python closure local variables

Categories