1

I'm having a trouble with running script, where print is a callback function to event loop

from pygame.locals import KEYDOWN
import pygame


def event_loop(handle_key, delay=10):
        """Processes events and updates callbacks."""
        while True:
            pygame.event.pump()
            event = pygame.event.poll()
            if event.type == KEYDOWN:
                handle_key(event.key)
            pygame.time.delay(delay)


if __name__ == '__main__':
        pygame.init()
        pygame.display.set_mode((640, 400))
        event_loop(print)

I get syntax error:

event_loop(print)
               ^
 SyntaxError: invalid syntax
Wirman:04_scientific_method mac$ python event_loop.py
 File "event_loop.py", line 23
   event_loop(print)
                  ^
SyntaxError: invalid syntax

Any help would much appreciated

Wirman
  • 13
  • 2
  • 2
    What you are doing is conceptually [this](https://stackoverflow.com/questions/21035437), but as that question shows, it should work. But in Python 2.7 `print` (famously!) is not a function. Any chance of upgrading? If not, you need to add a wrapper function that performs your `print`. – Jongware Mar 02 '20 at 00:33
  • 2
    Python-2.7 is EOL. Please upgrade – OneCricketeer Mar 02 '20 at 02:57

1 Answers1

0

In Python 2.7 (which has been deprecated since 2015 and has officially reached End of Life per Januari 1, 2020), print used to be a statement, just like a couple of other keywords such as break and continue. In newer versions of Python since 3.0 onwards, print is a function, and that is why you may see examples of your callback that use print itself.

So you get a SyntaxError because you are applying a modern construction (post-2015 v.3) to an old and officially obsolete version of Python.

If you want to keep on using 2.7, you can work around it by creating a wrapper function for just the print statement:

def my_print (text):
  print text

def event_loop (handle_key):
  handle_key('hello!')

event_loop(my_print)

where replacing the last line with your original line

event_loop(print)

will show that SyntaxError again. But it would be better to upgrade.

Jongware
  • 21,685
  • 8
  • 47
  • 95