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

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.

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.

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?

Nested functions and parent variables? [duplicate]

This question already has answers here:
Why can't Python increment variable in closure?
(3 answers)
Read/Write Python Closures
(8 answers)
Closed 5 years ago.
When I run the code below:
def run():
test = False
def tester():
if not test:
print("test is false")
else:
print("test is true")
test = not test
tester()
run()
I get the error:
local variable 'test' referenced before assignment
I was under the impression that the child function would have access to the parent functions variables. After playing with this code a bit I've found that if I remove the assignment (test = not test) then everything works fine.
Why does having an assignment in the child function break this code? If I shouldn't have the assignment in the child function, what would be the best way to toggle the test flag? Should I just return a value from the child function and use that to toggle test?
Python 2 doesn't support assignments to variables closed over by a nested function. The usual workaround is to put the value in a mutable container (e.g., a one-element list). Python 3 offers the nonlocal keyword for this purpose.

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.

conditional referencing of Python packages: UnboundLocalError [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)
Closed 7 years ago.
I would like to use function of same name from different packages dependent on a function flag:
import chainer.functions as F
def random_q_z(input, test = False):
if test:
F = np
# ...
else:
# ...
pass
return F.sum(input)
However the interpreter protests:
UnboundLocalError: local variable 'F' referenced before assignment
How to please it and do conditional referencing of packages?
I see that this question relates to other questions on variable scopes, but here the question is about how to handle different scopes. And the answer I got is valuable for this particular question.
Make F a default parameter:
import chainer.functions as F
def random_q_z(input, test=False, F=F):
if test:
F = np
return F.sum(input)
If you don't provide F as an argument when calling random_q_z, chainer.functions is used. You can also give random_q_z a different function for F.

Categories