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.

3
  • 1
    Is there any missing code? The 'child' variable in the sixth line is out of scope. Commented Dec 15, 2016 at 3: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? Commented Dec 15, 2016 at 3:23
  • 1
    Thanks for @wwii , i think his answer is precise. It is a interesting feature in Python. Commented Dec 15, 2016 at 5:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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!

4 Comments

Why would C# scoping rules apply to Python?
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-- 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.
Should I delete this answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.