1

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Rudolf Lovrenčić
  • 147
  • 1
  • 2
  • 9
  • Does this answer your question? [Short description of the scoping rules?](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – Karl Knechtel Sep 10 '22 at 10:00
  • "Why is nonlocal not the solution here?" Because the name `result` is global, in turn because `with` blocks **do not create a scope**. Neither do loops, `if` blocks, `try` blocks (although `try` blocks have a special hack to clean up names after `except` in more recent versions) or classes. Only functions (and comprehensions/generators in more recent versions) do. – Karl Knechtel Sep 10 '22 at 10:01

0 Answers0