Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another UnboundLocalError: local variable referenced before assignment Issue

I stumbled upon a situation that shutters my understanding of Pythons variable scope.

Here is the code:

transaction_id = None


def parseFileContent(hostID,marketID, content, writeToDB=False):
    features = _buildObjects(StringIO.StringIO(content))

    for feature in features:
        featureID =  adapter.addFeature(feature.name,boris)
        print transaction_id #breaks here UnboundLocalError: local variable 'transaction_id' referenced before assignment

        transaction_id = adapter.addFeatureTransactionToQueue(featureID, result[0], result[1], Command.ADD, boris, trans_id = transaction_id)

If I replace last line with

       adapter.addFeatureTransactionToQueue(featureID, result[0], result[1], Command.ADD, boris, trans_id = transaction_id)

Everything works. I need to understand what python dislikes about me printing the value in the first scenario.

like image 272
bioffe Avatar asked Dec 13 '25 18:12

bioffe


1 Answers

The Python compiler marks a name as local to a function if you assign to it. Your last line assigns to transaction_id so it is seen as a local name, not a global.

You need to tell the compiler explicitly that transaction_id is a global, by using the global keyword inside the function:

def parseFileContent(hostID,marketID, content, writeToDB=False):
    global transaction_id

If there is no assignment, a name is considered non-local instead and you do not need to mark it.

like image 77
Martijn Pieters Avatar answered Dec 15 '25 08:12

Martijn Pieters