Goal
I am trying to write a function where one or more of the input parameters is a global variable that is updated by the function, without having to return
values from within the function. I am aware I could just return a tuple or two separate values from the function, but I think updating the global variables from within the function would be another interesting method if it is possible.
Reason to do this
Updating global variables with a function is easy when the global variable is known (ie. defined previously in the python script). However, I want to define the function in a separate .py file to easily use the function within other python scripts. Therefore, I need to be able to support different variable names to update.
While this is not at all necessary, I am just interested if this is even possible.
Example Pseudocode
I'm thinking something like this:
def math_function(input_val, squared_result, cubed_result):
squared_result = input_val**2 #update the var input as the squared_result parameter
cubed_result = input_val**3 #update the var input as the cubed_result parameter
where you would input a number for input_val
and then global variables for squared_result
and cubed_result
that the function updates with the result. It would then theoretically work like:
#Declare global variables
b = 0
c = 0
#then somewhere in the code, call the function
math_function(2, b, c)
#check the new values
print(b) #Output: b = 4
print(c) #Output: c = 8
This would allow me to use the function in different python scripts without having to worry about what order the results are returned in.
CodePudding user response:
First: I am in no way advocating this.
You could use the globals
builtin function to access a global variable by name:
def gtest(name,value):
globals()[name] = value
gtest('new_global','new_value')
print(new_global)
CodePudding user response:
"""
Modify globals
"""
b = 0
c = 0
def math_function(input_val, global_name_1, global_name_2):
globals()[
global_name_1] = input_val ** 2 # update the var input as the squared_result
# parameter
globals()[global_name_2] = input_val ** 3 # update the var input as the
# cubed_result parameter
math_function(2, 'b', 'c')
print(b)
print(c)
Output
4
8