4

My professor had mentioned that it's possible to pass functions like print as a parameter, but when I try and actually implement it I get a syntax error. Is it something small that I am missing here?

 def goTime(sequence, action):
    for element in sequence:
       action(element)

 def main():
    print("Testing Begins")
    test = list ( range( 0 , 20, 2) ) 
    goTime(test, print)
    print("Testing Complete")

Upon running the following, I receive this syntax error:

goTime(test, print)
                 ^
SyntaxError: invalid syntax

If I define my own function that uses print, it works, like so:

def printy(element):
   print(element)

def goTime(sequence, action):
   for element in sequence:
      action(element)

def main():
   print("Testing Begins")
   test = list ( range( 0 , 20, 2) ) 
   goTime(test, printy)
   print("Testing Complete")
mhlester
  • 22,781
  • 10
  • 52
  • 75
Talen Kylon
  • 1,908
  • 7
  • 32
  • 60

4 Answers4

5

In Python 3 that will work out of the box. In Python 2.7 however, you can do:

from __future__ import print_function
def foo(f,a):
    f(a)

foo(print,2)
2

Note that in Python2.7 after you do from __future__ import print_function you won't be able to use print like a keyword any more:

>>> from __future__ import print_function
>>> print 'hi'
  File "<stdin>", line 1
    print 'hi'
             ^
SyntaxError: invalid syntax

Although I think your professor only wanted to make a point that functions in Python are first class citizens (ie: objects) and they can be passed around as any other variable. He used a controversial example though :)

Hope this helps!

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
1

You can't pass print in Python2, because it's a keyword rather than a function. It's possible in Python3.

You can try to import new print function from future. Check this question:

How to gracefully deal with failed future feature (__future__) imports due to old interpreter version?

and then you can use it as a function.

Community
  • 1
  • 1
gruszczy
  • 40,948
  • 31
  • 128
  • 181
0

You can try sys.stdout

import sys

def printy(element):
    sys.stdout.write(str(element)+'\n')
afkfurion
  • 2,767
  • 18
  • 12
0

In python2 You can wrap print inside of a wrapper function and pass that:

def PrintWrapper(arg):
    print(arg)

def MyFunc(x, func):
    func(x)

# call the function with the wrapper as an argument
MyFunc("Hello world", PrintWrapper)