开发者

Assign pass to a function in Python

I have a piece of code that defines a function that takes a function as an argument, like so:

def stuff(n, f):
  f(n)

Now, I want to provide some default value of f that does nothing. So I figured I'd use pass, like so:

def stuff(n, f = None):
  if(f is None):
    f = pass
  f(n)

But th开发者_如何学Pythonis does not compile. How should I be doing this?


The pass is a keyword for the interpreter, a place holder for otherwise nothing. It's not an object that you can assign. You can use a no-op lambda.

f = lambda x: None


Why not simply this ?

def stuff(n, f=None):
    if f is None:
        return
    return f(n)


A little shorter:

def stuff(n, f=None):
  f = f or (lambda x: None)
  f(n)

Or even better:

def stuff(n, f=None):
    f(n) if f is not None else None


You can't assing empty. But you can creaty internal function, that you will assign to f.

def stuff(n, f=None):
  def empty(n):
    pass
  if f is None:
    f = empty
  f(n)


The generic noop function :

f = lambda *x,**y:None

You can call

f()
f(0,foo=0)


I'd go with a

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

def algo(func=nop):
    do_something()
    func()
    do_something_else()

algo() # nop is called
algo(some_callback) # some_callback is called

IMHO looks cleaner than

if foo:
    foo()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜