0 votes
1 view
in Python by (47.8k 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 (107k 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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...