Type checks should be avoided in Python (search about "duck typing" on that). When they are necessary, it should usually be done with isinstance
rather than an equality check on the type like the question shows. This has the advantage of being more flexible for inheritance situations.
Since Python 3.4, the string-like branch and the dict-like branch can be written in separate functions using stdlib functools.singledispatch
.
So instead of:
def aFunction(input_):
if isinstance(input_, str):
print('you gave a string-like input')
...
elif isinstance(input_, dict):
print('you gave a dict-like input')
...
You can now have:
from functools import singledispatch
@singledispatch
def aFunction(input_):
pass
@aFunction.register(str)
def _(input_):
print("you gave a string-like input")
@aFunction.register(dict)
def _(input_):
print("you gave a dict-like input")
In Python 3.5+ you have another option of using type hinting function annotations. Read PEP 484 - Type Hints for more details about that feature. It means the single dispatch generic function above can be written as:
from functools import singledispatch
@singledispatch
def aFunction(input_):
pass
@aFunction.register
def _(input_: str):
print("you gave a string-like input")
@aFunction.register
def _(input_: dict):
print("you gave a dict-like input")
input
argument (now it overwrites a built-in function). – Agapanthus