I am using a method for storing and recalling global variables in Python. I like it. It seems to work for me. I am not a coder though. I know nothing about this stuff. So, wondering where its limitations will be - how and when I will regret using it in future.
I create a function that will update the value if passed a new one or return the existing value as below:
def global_variable(new_value = None):
# a function that both stores and returns a value
# first deal with a new value if present
if new_value != None
# now limit or manipulate the value if required
# in this case limit to integers from -10 to 10
new_value = min(new_value, 10)
global_variable.value = int(max(new_value, -10))
# now return the currently stored value
try:
# first try and retrieve the stored value
return_value = global_variable.value
except AttributeError:
# and if it read before it is written set to its default
# in this case zero
global_variable.value = 0
return_value = global_variable.value
# either way we have something to return
return return_value
store like this
global_variable(3)
retrieve like this
print(global_variable())
global_variable(x)is the same assingleton.value = xandglobal_variable()is the same assingleton.value.