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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With