Assign pass to a function in Python

2.8k views Asked by At

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 this does not compile. How should I be doing this?

6

There are 6 answers

3
Keith On BEST ANSWER

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
0
gruszczy On

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)
7
Nicolas Lefebvre On

Why not simply this ?

def stuff(n, f=None):
    if f is None:
        return
    return f(n)
9
Björn Pollex On

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
0
Alcolo47 On

The generic noop function :

f = lambda *x,**y:None

You can call

f()
f(0,foo=0)
0
Ivan Dives On

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()