Are Python’s built-in functions not available for use as keyword defaults, or should I be using some other way of referring to a function?
I wanted to write a function like this:
def isPNGBlock(bytes, blockLen, pngOffset=0, pngErrorLogger=print):
...
try:
r.validate_signature()
width, height, pixels, metadata = r.read(lenient=True)
except png.Error as e:
pngErrorLogger(e)
Instead I’ve had to settle for doing this with a default argument of None as a flag value.
def isPNGBlock(bytes, blockLen, pngOffset=0, pngErrorLogger=None):
...
try:
r.validate_signature()
width, height, pixels, metadata = r.read(lenient=True)
except png.Error as e:
if pngErrorLogger is None:
print(e)
else:
pngErrorLogger(e)
or using a wrapper function:
def defaultLogger(str):
print(str)
def isPNGBlock(bytes, blockLen, pngOffset=0, pngErrorLogger=defaultLogger ):
...
try:
r.validate_signature()
width, height, pixels, metadata = r.read(lenient=True)
except png.Error as e:
pngErrorLogger(e)
They are available to use just like any other function.
However, in Python 2
printis a statement, not a function. It became a function in Python 3, so your code will work there. It will also work in recent versions of Python 2 if you usefrom __future__ import print_function. For example, using Python 2.7.3:If you can’t use
printas a function, you could either write a wrapper, or usesys.stdout.write: