9

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

4 Answers 4

12

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
1
  • 2
    I think function objects are mutable which makes me believe this is a tricky idea. I wouldn't make it the default argument like that (instead use a function object that is re-created) unless I'm sure no one can access and change it... Sep 15, 2015 at 10:28
2

This should work:

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

myInstance = myClass()
2

I used the following:

a=lambda:None
a()
print a()

The latter line prints None.

0

This worked for me:

def none(function=True): if function==True: return None else: function()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.