0
def pretty(e, level=0):
    if len(e) > 0:
        e.text = '\n' + '\t' * (level + 1)
        for child in e:
            pretty(child, level + 1)
        child.tail = child.tail[:-1]
    e.tail = '\n' + '\t' * level

This Python function uses a recursive call in its 5th line. It has a for-loop in the function with a loop variable called child. But in its 6th line, it has a child variable too. Please help me understand where child was defined.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
Y.Eric
  • 3
  • 1
  • 1
    Is there any missing code? The 'child' variable in the sixth line is out of scope. – Jacob G. Dec 15 '16 at 03:18
  • 2
    ```child``` will be the very last child in ```e``` - the last child of the for loop. Try ```for thing in '1234': pass``` - when the loop finishes what is `thing`? – wwii Dec 15 '16 at 03:23
  • 1
    Thanks for @wwii , i think his answer is precise. It is a interesting feature in Python. – Y.Eric Dec 15 '16 at 05:34

2 Answers2

2

When the loop is finished, the last element of the iterable e has been assigned to child. Since the smallest enclosing scope is the body of the function (for loops do not create their own scopes in Python), child is still in scope in the 6th line.

Community
  • 1
  • 1
ad absurdum
  • 19,498
  • 5
  • 37
  • 60
1

The variable 'child' is a variable declared inline by the 'for'.

Have a look at this c# example:

     foreach (PuzzlePiece **piece** in myPuzzle.pieces)
     {
        piece.DoSomething();
        Console.WriteLine( piece.WhatNumberPieceAmI());
     }

The Foreach is creating a scoped variable that will exist within the Foreach scope { }.

You are looking at the equivalent thing in your Python code.

Good Luck!

Monza
  • 745
  • 4
  • 12
  • 2
    Why would `C#` scoping rules apply to Python? – ad absurdum Dec 15 '16 at 03:45
  • I know the variable 'child' in 5th line , it is a scoped variable in for-loop. but in 6th line , this 'child' is out of the for-loop obviously, so i can't understand where it was defined – Y.Eric Dec 15 '16 at 05:17
  • @Y.Eric-- No. The scope of `child` is definitively _not_ the body of the `for` loop. There is no such thing as `for`-loop-scope in Python. The scope of `child` is the body of the function `pretty`. A few of us keep trying to tell you this. The answers and comments that suggest that `child` in line 6 and `child` in line 5 are in different scopes are wrong. This is a common misunderstanding because there are many languages that _do_ scope the body of `for` loops. Just not Python. – ad absurdum Dec 15 '16 at 07:08
  • Should I delete this answer? – Monza Dec 15 '16 at 20:46