0

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())

10
  • 4
    Why not just use a global variable? Commented May 2, 2019 at 16:58
  • What problem are you trying to solve with this? Commented May 2, 2019 at 16:59
  • 1
    This function you've written would be much better off being a class. Commented May 2, 2019 at 17:04
  • If instead of 1 global variable you wanted 100, you would need to write this function again and again and again.... with different names each time. Just using global variables is way easier BUT if you wanted to keep going with this object that stores global variables for you, I would suggest a class instead of just a function. That would allow you to extend this to 100s of variables without all the tedious work. Commented May 2, 2019 at 17:04
  • This is something like defining a property for a class which you will only create one instance for; global_variable(x) is the same as singleton.value = x and global_variable() is the same as singleton.value. Commented May 2, 2019 at 17:06

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.