python - Short Description of the Scoping Rules? -


what exactly python scoping rules?

if have code:

code1 class foo:    code2    def spam.....       code3       code4..:        code5        x() 

where x found? possible choices include list above:

  1. in enclosing source file
  2. in class namespace
  3. in function definition
  4. in loop index variable
  5. inside loop

also there context during execution, when function spam passed somewhere else. , maybe lambda functions pass bit differently?

there must simple reference or algorithm somewhere. it's confusing world intermediate python programmers.

actually, concise rule python scope resolution, learning python, 3rd. ed.. (these rules specific variable names, not attributes. if reference without period, these rules apply)

legb rule.

l, local — names assigned in way within function (def or lambda)), , not declared global in function.

e, enclosing-function locals — name in local scope of , statically enclosing functions (def or lambda), inner outer.

g, global (module) — names assigned @ top-level of module file, or executing global statement in def within file.

b, built-in (python) — names preassigned in built-in names module : open,range,syntaxerror,...

so, in case of

code1 class foo:    code2    def spam.....       code3       code4..:        code5        x() 

the loop not have own namespace. in legb order, scopes

l : local, in def spam (in code3, code 4, code5).

e : enclosed function, enclosing functions (if whole example in def)

g : global. there x declared globally in module (code1)?

b : builtin x in python.

x never found in code2 (even in cases might expect would, see antti's answer or here).


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -