Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

What exactly are the Python scoping rules?

If I have some code:

Code1

class Foo:

Code2

def spam.....

Code3

for code4..:

Code5

x()

Where is x found? Some possible choices include the list below:

  1. In the enclosing source file

  2. In the class namespace

  3. In the function definition

  4. In the for the loop index variable

  5. Inside the for loop

Also, there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?

There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.

1 Answer

0 votes
by (106k points)

There is a concise rule for Python Scope resolution, These rules are specific to variable names, not attributes. To apply these rules you need to reference it without a period:-

What is LEGB Rule:-

L, Local:-

Local is the names assigned within a function (def or lambda), and not declared global in that function.

E, Enclosing-function locals:-

It is the local scope of any and all statically enclosing functions (def or lambda), from inner to outer.

G, Global (module):-

The names assigned at the top-level of a module file, or by executing a global statement in a def within the file.

B, Built-in (Python):-

Here the names are preassigned.

open,range,SyntaxError,...

So, in your code:-

Code1

class Foo:

       Code2

       def spam.....

           Code3

           for code4..:

                Code5

                x()

In your code, the LEGB order is as follows:-

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

E: Enclosed function, any enclosing functions (if the whole example were in another def)

G: Global. Was there any x declared globally in the module (code1)?

B: Any builtin x in Python.

The function x will never be found in code2.

Related questions

0 votes
1 answer
0 votes
4 answers
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...