0

I would like to write one function which as argument takes one variable, say x. Now I would like to use this function in such a way that I can pass any global variable and its value will change after execution of this function. So I would like to get sth like that:

y = 2
def f(x):
    global x
    x = 2 * x

In the above code of course will not work because I have to pass global y instead of `global x' but if I want to use the same funtion for many variables then this is problematic. What can I do?

Degeleqgo
  • 15
  • 5
  • 3
    Don't do this, it is a terrible program design decision and it is completely unecessary. Note, you **do not pass variables to functions, you pass objects**. The *reasonable* way to do this is to have your function *return an appropriate value* and the *caller* is responsible for assigning to the required variable in the caller's scope – juanpa.arrivillaga Mar 23 '22 at 20:22
  • 2
    Note, this is technically possible with global variables, but again, **this is highly, highly inadvisable** – juanpa.arrivillaga Mar 23 '22 at 20:23
  • See https://stackoverflow.com/q/986006/5987 – Mark Ransom Mar 23 '22 at 20:25
  • Python functions are called by value, not by reference to variables. So the function can't reassign the original variable. And what would you expect if it were called `f(3)`? – Barmar Mar 23 '22 at 20:25
  • I'm writing tkinter app so when I for example want to get path of a file then I need to make this `path` variable global. Generally in tkinter its easiest to work with function which do not return anything – Degeleqgo Mar 23 '22 at 20:25
  • In Tkinter use a `StringVar` or `IntVar` object. – Barmar Mar 23 '22 at 20:26
  • 1
    @Degeleqgo "I'm writing tkinter app so when I for example want to get path of a file then I need to make this path variable global." *no you don't*. Using `tkinter` absolutly does not require global, mutable state. Again, this is a *well known, classic anti-pattern*. Don't do it. – juanpa.arrivillaga Mar 23 '22 at 20:36

0 Answers0