Reputation: 154
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
global_variable(3)
print(global_variable())
Upvotes: 0
Views: 50
Reputation: 79
You can just use global variables. If you need to change them within a function you can use the global keyword:
s = 1
def set():
global s
s = 2
print(s)
set()
print(s)
> 1
> 2
Upvotes: 2