I know python function arguments are passed by reference and mutable arguments can modify the out-of-scope variable inside the function, except if you rebind the local variable.
My issue is that I want to cast the function argument to a different type and affect the out-of-scope variable that got passed. But both ways that I tried just rebind the local in-scope argument.
def change_type(my_var):
try:
if float(my_var) > 0:
my_var = float(my_var) #just rebinds!
except ValueError:
pass
some_var = '0.5'
change_type(some_var)
print(type(some_var)) #gives 'str'; I want it to be 'float'
I also tried just doing float(my_var)
without assignment in the if
block but that didn't do anything either.
Is there any way for me to modify the data type of an out-of-scope variable like this, or must I do it directly on some_var
outside of my function?
Thanks!