Skip to content
Advertisement

Python: more elegant way to assert type of function input

I am a complete beginner in Python… Currently I am trying to write a function which first checks whether the inputs x and y are int or float.

My guess which does the job is

if (type(x) != int and type(x) != float) or (type(y) != int and type(y) != float):

However, this seems quite clumsy / inefficient to me and will be difficult to generalise in case of many inputs. Therefore I think there should be a more elegant way to write this condition..? Thank you for any ideas!

Advertisement

Answer

Use isinstance:

if not isinstance(x, (int, float)) and not isinstance(y, (int, float)):
    # do something..

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement