Accessing function-local variable

Question:

This code

def reportRealDiagnostics():

        ranks = 0
        class Rank: 
            def __init__(self):
                global ranks
                ranks += 1
        rank = Rank()

reportRealDiagnostics()

produces

NameError: global name 'ranks' is not defined

I am sure that this is all what you need to answer the question.

Asked By: Val

||

Answers:

You should use variable as nonlocal:

nonlocal ranks
Answered By: Danil Speransky

When you use global ranks it looks for ranks in the global scope not in enclosing scope, so you get that error. The ranks you’ve defined is part of the enclosing scope.

In Python3 this has been resolved and you can modify ranks by using the nonlocal keyword:

def reportRealDiagnostics():
        ranks = 0
        class Rank: 
            def __init__(self):
                nonlocal ranks
                ranks += 1
        rank = Rank()

reportRealDiagnostics()

In Python2 you can define it as a function attribute:

def reportRealDiagnostics():
        class Rank: 
            def __init__(self):
                reportRealDiagnostics.ranks += 1
        rank = Rank()
reportRealDiagnostics.ranks = 0
reportRealDiagnostics()

There are some other alternatives too: nonlocal keyword in Python 2.x

Answered By: Ashwini Chaudhary