I have the following code for receiving messages from RabbitMQ message queue:
import pika
HOST = 'localhost'
QUEUE = 'hello'
with pika.BlockingConnection(pika.ConnectionParameters(host=HOST)) as conn:
with conn.channel() as channel:
channel.queue_declare(queue=QUEUE)
result = ''
def callback(channel, method, properties, body):
nonlocal result
result = body
channel.stop_consuming()
channel.basic_consume(queue=QUEUE,
on_message_callback=callback,
auto_ack=True)
channel.start_consuming()
print("Recieved '{}'".format(result))
I get SyntaxError: no binding for nonlocal 'result' found
error on a nonlocal
statement. This answer uses the nonlocal
in, I think, exactly the same way. global
works fine in this case which I do not understand. Why is nonlocal
not the solution here?