0

I'm working on something in python where I need to use a global variable that is changed by a function. However, when I try to change the value inside the function, python instead creates a new local variable instead of accessing the global one.

For example, if I had the following useless function, it would give an error of "local variable 'x' referenced before assignment"

x=5
def example():
#This would of course normally use += but that's not applicable to my actual code
  x=x+5

Is there a way to tell python I want to access the existing variable rather than create a new one? I know I could pass it as a parameter but this is much more intuitive with how the code is structured

4
  • You need a global x statement inside the function, as otherwise the fact that the function assigns to the variable would make it a local. Commented Oct 16, 2024 at 16:33
  • Fixed it, thank you Commented Oct 16, 2024 at 16:36
  • Although you need global in this case, actually you probably don't want to do that (global variables are evil!). In most cases if you need to access a variable inside a function, the best way is to pass that variable as a parameter. Another option is encapsulate the function inside a class. Then you can make the variable x an attribute of the class and you can access it inside the method example doing self.x. So in short: You can solve what you want to do using global, but you probably should not do it. Commented Oct 16, 2024 at 16:43
  • Using mutable global state is a classic antipattern that should be avoided. Commented Oct 16, 2024 at 19:35

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.