1

I have a function that should operate according to the type of argument passed into it, simply illustrated:

def operate_according_to_type(argument_passed): 
    if type(argument_passed) == str:
        do string stuff
    elif type(argument_passed) == dict:
        do dict stuff
    elif type(argument_passed) == function:
        argument_passed()

def my_function(): pass

operate_according_to_type("Hello world")
operate_according_to_type({"foo": "bar"})
operate_according_to_type(my_function)

Now while type("Hello world"), type({"foo": "bar"}) and type(my_function) will return respectively <class 'str'>, <class 'dict'> and <class 'function'>, I can't seem to compare to function just as I can to str, the word is not even "reserved".

How should I proceed? Should I proceed at all or is this just plain hazardous?

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119

1 Answers1

1

You can check if the object is callable using the callable built-in function:

...
elif callable(argument_passed):
    argument_passed()

More details can be found here.

Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50