Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables declared outside function [duplicate]

Tags:

python

Possible Duplicate:
referenced before assignment error in python
local var referenced before assignment

I was just trying to see how variable scopes work and ran into the following situation (all ran from the terminal):

x = 1 def inc():     x += 5  inc() Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "<stdin>", line 2, in inc UnboundLocalError: local variable 'x' referenced before assignment 

I was thinking maybe I don't have access to x in my method, so I tried:

def inc():     print(x)  1 

So this works. Now I know I could just do:

 def inc():      global x      x += 1 

And this would work, but my question is why does the first example fail? I mean I would expect since print(x) worked that x is visible inside the function so why would the x += 5 fail?

like image 983
Bogdan Avatar asked Jan 20 '12 15:01

Bogdan


People also ask

Can I declare a variable outside function?

In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

When the variable declared outside to the function is called?

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their type throughout the life-time of your program. A global variable can be accessed by any function.

What happens if you modify a variable outside the function?

1 Answer. When a function depends on variables or functions outside of its definition block, you can never be sure that the function will behave the same every time it's called. In the above example the value of y get changed inside the function definition due to which the result will change each time.

How do you access the variables outside a function in Python?

To access a function variable outside the function without using "global" with Python, we can add an attribute to the function. to add the bye attribute to the hi function. We can do this since functions are objects in Python. And then we get the value with hi.


1 Answers

Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global, nonlocal, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.

Here are some examples regarding global:-

>>> global_var = 5 >>> def fn(): ...     print(global_var) ...  >>> fn() 5 >>> def fn_2(): ...     global_var += 2 ...     print(global_var) ...  >>> fn_2() Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "<stdin>", line 2, in fn_2 UnboundLocalError: local variable 'global_var' referenced before assignment >>> def fn_3(): ...     global global_var ...     global_var += 2 ...     print(global_var) ...  >>> fn_3() 7 

The same patterns can be applied to nonlocal variables too, but this keyword is only available to the latter Python versions.

In case you're wondering, nonlocal is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def within a def, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...

Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner defs using the same variable names as the outer ones, which just should just be avoided to be honest.

like image 80
Louis Avatar answered Sep 29 '22 23:09

Louis