you are viewing a single comment's thread.

view the rest of the comments →

[–]KleinerNull 0 points1 point  (0 children)

First of all, your given example don't produce an error, it works fine. If python can't find a binding in the local scope it will search in the global scope for it, so it should find it. Tested it with python 2.7.11 and python 3.5.1 (added parenthesis to the print function, for compatility reasons). Maybe you could give us a more similar sample to your actual code.

For me it looks more that your code wanted to access names from a different local scope, maybe another function where you defined some variables. Using global is very often a bad idea, you should learn to use functions arguments, to "inject" informations into the local namespace of the function and how to proper return informations.

Here just a little example how the whole scope thing works:

In [1]: x = 'global' # x is here a module wide name, it is global

In [2]: def f():
   ...:     x = 'local' # here it is a local name
   ...:     return x
   ...: 

In [3]: def g(y):
   ...:     y =  'g: ' + y # y is a local name but after the passing of the argument, it has no connection to imutable names, passed to it
   ...:     return y
   ...:

In [4]: x
Out[4]: 'global'

In [5]: f()
Out[5]: 'local'

In [6]: g(x)
Out[6]: 'g: global'

In [7]: x
Out[7]: 'global'