I wrote a test program that looked like this:
#!/usr/bin/python
def incrementc():
c = c + 1
def main():
c = 5
incrementc()
main()
print c
I’d think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get
Traceback (most recent call last):
File "test.py", line 10, in <module>
main()
File "test.py", line 8, in main
incrementc()
File "test.py", line 4, in incrementc
c = c + 1
UnboundLocalError: local variable 'c' referenced before assignment
Why isn’t c passing through? And if I want a variable to be referenced by multiple functions, do I have to declare it globally? I read somewhere that global variables are bad.
Thanks!
You’re thinking of dynamic scoping. The problem with dynamic scoping is that the behavior of
incrementcwould depend on previous function calls, which makes it very difficult to reason about the code. Instead most programming languages (also Python) use static scoping:cis visible only withinmain.To accomplish what you want, you’d either use a global variable, or, better, pass
cas a parameter. Now, because the primitives in Python are immutable, passing an integer can’t be changed (it’s effectively passed by value), so you’d have to pack it into a container, like a list. Like this:Or, even simpler:
Generally, global variables are bad because they make it very easy to write code that’s hard to understand. If you only have these two functions, you can go ahead and make
cglobal because it’s still obvious what the code does. If you have more code, it’s better to pass the variables as a parameter instead; this way you can more easily see who depends on the global variable.