jen007
jen007

Reputation: 1589

python scoping - child scope should have access to parent scope?

From what I read here, child scope should have access to variables defined in the parent scope. However, in my case, I get an unresolved error on count. Any reason why this happened?

def find_kth_largest_bst(root, k):
        count = 0
    def _find_kth_largest_bst(root, k):
        if not root:
            return None

        _find_kth_largest_bst(root.right, k)
        count += 1 #unresolved error here??
        pass

Upvotes: 1

Views: 369

Answers (2)

Guinther Kovalski
Guinther Kovalski

Reputation: 1919

what you are doing is using Inner Functions, which is different from class inheritance. Another quastion very similar is this one:

Python nested functions variable scoping

from this question one answer says:

" The documentation about Scopes and Namespaces says this:

A special quirk of Python is that – if no global statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects.

it means that you may solve your error with global or nonlocal statement

def find_kth_largest_bst(root, k):
    global count
    count = 0
    def _find_kth_largest_bst(root, k):
        if not root:
            return None

        _find_kth_largest_bst(root.right, k)
        count += 1 #unresolved error here??
        pass

Another thing here is that count = 0 have double tab, or 8 spaces, while it should have only one.

Upvotes: 0

D Dhaliwal
D Dhaliwal

Reputation: 552

You can use nonlocal keyword to access variables from parent scope.

def find_kth_largest_bst(root, k):
    count = 0
    def _find_kth_largest_bst(root, k):
        nonlocal count  # This will access count from parent scope
        if not root:
            return None

        _find_kth_largest_bst(root.right, k)
        count += 1
        pass

Upvotes: 2

Related Questions