Reputation: 4706
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 ?
Upvotes: 17
Views: 13232
Reputation: 155448
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
.
Upvotes: 16