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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Sorry for the duplicate. Is a case like the example considered bad practice overall or is it fine?
@PierreMDL checking the type of a parameter is never a bad practice :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.