Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a python construct that is a dummy function?

Is there a python construct that corresponds to a function taking no argument, doing nothing and returning nothing ? Something similar to object None but that would be a function instead of an object ?

The context

I want to define a class where the constructor gets a function as an argument and references it to a class attribute. Upon instanciation, the user decides whether he/she wants that function to be an actual function which he/she defines him/herself or leave the default which is to call a dummy function which does nothing.

Here is what I have now :

def sayHello():
    print("hello world !")

def doNothing():
    pass

class myClass:
    def __init__(self, myFunc):
        self.doIt = myFunc

myInstance = myClass(sayHello)
myInstance.doIt()
myInstance = myClass(doNothing) # Works but requires defining function doNothing()
myInstance.doIt()
#myInstance = myClass(None) # Returns error "'NoneType' object is not callable"
myInstance.doIt()
like image 670
Gael Lorieul Avatar asked Sep 15 '15 09:09

Gael Lorieul


1 Answers

How about lambdas?

myInstance = myClass(lambda:None)

Sure you can pass is as default to your __init__ function:

class myClass:
    def __init__(self, myFunc = lambda:None):
        self.doIt = myFunc
like image 68
Alexander Mihailov Avatar answered Sep 19 '22 18:09

Alexander Mihailov