16

I am currently trying to understand this piece of code in python

def foo(a):
  if a==12:
    var = "Same"
  else:
    var = "different"

I read and understand the fact that python does not support block based scoping. So everything created inside a function (whether inside a loop or conditional statements) is openly available to other members of a function.I also read the scoping rules here . At this point would it be same to assume that these inner scoped variables are hoisted inside a functions just like they are hoisted in javascript ?

Community
  • 1
  • 1
James Franco
  • 4,516
  • 10
  • 38
  • 80
  • 1
    Well Python doesn't exactly have variable declaration to begin with, so it's hard to make comparisons to javascript's `var` hoisting. I do know you can put a `global x` declaration after assigning something to x and it will still work, but that's sort of apples-and-oranges. – Kevin Jun 22 '16 at 20:06
  • 1
    @jamesfranco -- it's never safe to assume. Why don't you fire up your python interpreter and find out? – Charles D Pantoga Jun 22 '16 at 20:23
  • @Kevin how's Python's declaration (or lack thereof) different to Javascript's, other than the `var` keyword? – Rob Grant Jun 22 '16 at 20:26

1 Answers1

16

You got it. Any name assigned inside a function that isn't explicitly declared with global (with Py3 adding nonlocal to indicate it's not in local scope, but to look in wrapping scopes rather than jumping straight to global scope) is a local variable from the beginning of the function (it has space reserved in an array of locals), but reading it prior to assignment raises UnboundLocalError.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • This also appears to apply at the top "module" level. I am just now reading a class that references a variable (a singleton, as it happens) defined after it in the file (!) – GreenAsJade Jul 26 '16 at 03:37
  • 2
    @GreenAsJade: That's only legal if the variable is referenced from within a function scope (because functions aren't actually executed at definition time, and look up their globals lazily when called). If it was referenced at global or class definition scope before it was defined, it would fail. – ShadowRanger Mar 13 '19 at 21:17