Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block Scoping in python - is it similar to javascript hoisting when inside a function?

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 ?

like image 294
James Franco Avatar asked Jun 22 '16 19:06

James Franco


People also ask

Does Python have function hoisting?

Python hoist() Calling hoist(f) transforms f , such that instead of returning the return value of f , it returns the values of all local variables in addition to the return value of f .

Is Python function scoped or block scoped?

Local (or function) scope is the code block or body of any Python function or lambda expression. This Python scope contains the names that you define inside the function. These names will only be visible from the code of the function.

Are Python classes hoisted?

No, there is no hoisting. However, for type annotations in older versions you can simply use a string, in newer versions, from __future__ import annotations which will give you the behavior of postponed evaluation of annotations.

Are JavaScript functions hoisted?

Declarations are moved to the top of the current scope by the JavaScript interpreter, meaning the top of the current function or scripts. All functions and variables are hoisted.


1 Answers

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.

like image 114
ShadowRanger Avatar answered Oct 19 '22 06:10

ShadowRanger