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:
- in enclosing source file
- in class namespace
- in function definition
- in loop index variable
- 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
Post a Comment