Josh
Josh

Reputation: 12791

Definition of a function that does nothing

I need to define a function depending on a condition, so that it either does something or nothing.

e.g.

# Code block that *defines* bar
if condition:
  bar = do_stuff
else:
  bar = # ?
# End of the definition of bar

bar()

do_stuff is a function defined somewhere else that does some useful computation. I want bar() to do be defined to do nothing if the condition above is not met. Any ideas?

Note: I designed the if-else block above for illustration purposes. I know that I could just call do_stuff() in the if body and pass in the else body. The code above is just to illustrate a code block after which I need bar to be defined either to do something or to do nothing. The block just defines the function and is not meant to call it.

Upvotes: 0

Views: 4476

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208495

To set the variable bar to be a function that does nothing, there are two options:

  • Using a lambda:

    bar = lambda: None
    
  • Using a function definition:

    def bar():
        pass
    

You could also use return None instead of pass for the function definition, the behavior is equivalent.

Upvotes: 7

BrenBarn
BrenBarn

Reputation: 251408

You can make a function that does nothing with:

def func():
    pass

Upvotes: 6

Related Questions