最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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 ?

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 ?

Share Improve this question edited May 23, 2017 at 12:25 CommunityBot 11 silver badge asked Jun 22, 2016 at 19:44 James FrancoJames Franco 4,70610 gold badges46 silver badges92 bronze badges 3
  • 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 Commented Jun 22, 2016 at 20:06
  • 1 @jamesfranco -- it's never safe to assume. Why don't you fire up your python interpreter and find out? – Charles Commented Jun 22, 2016 at 20:23
  • @Kevin how's Python's declaration (or lack thereof) different to Javascript's, other than the var keyword? – Rob Grant Commented Jun 22, 2016 at 20:26
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论