Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

python - lambda *args, **kwargs: None

consider:

blank_fn = lambda *args, **kwargs: None

def callback(x, y, z=''):
    print x, y, z

def perform_task(callback=blank_fn):
    print 'doing stuff'
    callback('x', 'y', z='z' )

The motivation for doing it this way is I don't have to put in logic to check if callback has been assigned because it defaults to blank_fn which just does nothing.

This works, but is there some reason I shouldn't do it? Is it pythonic? Is there a better way to do it? Is there a built-in for:

lambda *args, **kwargs: None
question from:https://stackoverflow.com/questions/18024503/lambda-args-kwargs-none

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to PEP8, you should "Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name." So, one thing I would change is:

def blank_fn(*args, **kwargs):
    pass

However, I think a more pythonic way to do this is:

def perform_task(callback=None):
    print 'doing stuff'
    if callback is not None:
        callback('x', 'y', z='z')

There shouldn't be any need to call a function that does nothing. Truth value testing is cheaper than function calling.

def do_nothing(*args, **kwargs): pass
def do_something(arg, callback=do_nothing):
    a = 1 + 2
    callback('z', z='z')
def do_something_else(arg, callback=None):
    a = 1 + 2
    if callback is not None:
        callback('z', z='z')

%timeit do_something(3)
1000000 loops, best of 3: 644 ns per loop

%timeit do_something_else(3)
1000000 loops, best of 3: 292 ns per loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...