0

I was thinking that variable can be only accessed after its declaration. But apparently, Python's name resolution starts to look for from inside to outer.

My question is that this is bad practice in terms of readability? I was wondering that this might be a common knowledge for Pythonista so that I can write this kind of code from now on.

def outer():
    def inner():
        print x
    x = ‘foo’
    inner()
>>> outer()
>>> ‘foo’
steve
  • 127
  • 12
  • You are right, that method is declared before defining `x` but it's only evaluated if you actually call the method (`inner()`) and at this point `x` is defined. – Jan Zeiseweis Oct 17 '17 at 09:22
  • Thanks! Is this bad practice? – steve Oct 18 '17 at 01:30
  • It kind of reminds me on getters and setters (https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters) I guess it depends on why you want to do it this way. You can't say per se that it's bad practice. – Jan Zeiseweis Oct 18 '17 at 07:38
  • Here is another use-case where it makes sense to do it this way: https://stackoverflow.com/questions/1589058/nested-function-in-python – Jan Zeiseweis Oct 18 '17 at 07:40

1 Answers1

0

When you invoke inner(), it starts executing. On line print x it sees variable name x. Then it looks to inner scope of function inner, doesn't find variable x there. Then it looks to the outer scope, namely, scope of outer. At this moment there is already variable x defined (as it is done before inner() invokation) and this variable is used.

Ilya V. Schurov
  • 7,687
  • 2
  • 40
  • 78
  • Thanks! I understand how python looks for variable. Is this common knowledge for Pythonista? In other words, I am wandering if this might be bad practice in terms of readability. Should I define variable before the function? – steve Oct 18 '17 at 01:28
  • Yes, you could call that "common knowledge". Any non-novice Python programmer _should_ be able to look at your code and understand what's going on. – alexis Oct 18 '17 at 13:47