简体   繁体   中英

Python builtin function as keyword argument default?

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)

Are Python's built-in functions not available for use as keyword defaults

They are available to use just like any other function.

However, in Python 2 print is 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 use from __future__ import print_function . For example, using Python 2.7.3:

In [2]: from __future__ import print_function

In [3]: def isPNGBlock(bytes, blockLen, pngOffset=0, pngErrorLogger=print):
   ...:     pngErrorLogger('test')
   ...:     

In [4]: isPNGBlock(0, 0)
test

If you can't use print as a function, you could either write a wrapper, or use sys.stdout.write :

In [7]: isPNGBlock(0, 0, 0, sys.stdout.write)
test

In Python 2, print is not a function, it is a statement. Statements can't be used as arguments.

In Python 3, print is a function and can be used the way you are doing it.

You can get the Python 3 behavior in Python 2 by doing from __future__ import print_function .

You are using python 2, where print is a keyword and not a function - and of course keywords cannot be passed around as arguments, or shadowed or modified. This has been changed in python 3, print is now a function where all of this is possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM