hafiz031
hafiz031

Reputation: 2720

How to change a variable's value inside a function and the value to be returned when the function is called?

Picture this situation: I have 3 files: file1.py, file2.py and file3.py. All the files are under the same package (possibly in different folders). Inside file1.py there is a function called getter() which has some local variable inside of it and the function returns its value when it is called. getter() is allowed to accept parameters if needed to set the value of that variable. During runtime, I want to set the value of that local variable by calling getter() from file2.py, such that whenever the getter() function is called from file3.py I get the latest set value from it. How to achieve it? Please note that the value is supposed to be updated multiple times, for each time file3.py should get the latest set value.

For demonstration, following is a draft presentation of what I want:

demo

Upvotes: 0

Views: 895

Answers (1)

aneroid
aneroid

Reputation: 15987

Use a global in file1.py which is set and returned by file1.getter(). The val needs to be an optional argument so that when getter is called to retrieve the value, it can be called without passing a value for val.

# in file1.py
_REAL_VAL = 10  # initial default value

def getter(val=None):
    global _REAL_VAL
    if val is not None:
        # set
        _REAL_VAL = val
    # get, or set+get
    return _REAL_VAL

The underscore _ before the name implies "internal use"/"private" so that other modules should not try to access or change it directly.

(And if you don't want it to return the value when it's being set, then put return _REAL_VAL in an else: clause. It will still implicitly return None as all Python functions would when there's no return value.)


Edit: Btw, "setting" with a "getter" is bad/silly. Use a property instead - which requires creating a class. You'll still maintain the instance globally.

# in file1.py

class Value:
    def __init__(self):
        self._val = None  # the real value

    @property
    def val(self):
        return self._val

    @val.setter
    def val(self, value):
        self._val = value


# is only executed once when imported
getter = Value()  # terrible name


# in file2.py, set it
file1.getter.val = 10

# in file3.py, get it
print(file1.getter.val)
# 10

It will be the same/only one instance of Value (getter) because the import file1 will only be executed once, even if imported many times:

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. (They are also run if the file is executed as a script.)

Upvotes: 1

Related Questions