0

Referencing this question: What's the canonical way to check for type in Python?

It is said that the best way to check for inputs is to not check them - that is to let try/except blocks take care of bad inputs.

My question is that if I want to design a function that handles multiple inputs, my intuition is to do something like this

def my_function(self, input):
    if isinstance(input, type):
        ...do this
    elif isinstance(input, type2):
        ...do that
    else
        print("can only handle type and type2")
        raise TypeError

but this is un-pythonic. How should I structure it?

In my specific use-case, I want to make a function that can handle a listor a pandas DataFrame, but from a function design POV, how should I design that in a try except paradigm? It kind of feels "ugly," but I also haven't seen code directly that does this in python yet.

frei
  • 495
  • 3
  • 19

2 Answers2

1

Here is a pretty simple example using assert to raise an error when the input is incorrect:

sentence = str(input("Please input some words: "))

assert len(sentence.split(" ")) > 1, "length of string less than 2 words"
Aero Blue
  • 518
  • 2
  • 14
1

That does not look functionally too "ugly", providing it adds no convoluted code and is readable.

But if you've multiple checks, you will end up adding more ifs. If you are worried about that, a dictionary approach seems legible also:

def call_integer():
    print('integer')

def call_str():
    print('str')

def my_function(input):
    val = map_dict.get(type(input).__name__, None)
    if val:
        val()
    else:
        print("can only handle type and type2")
        raise TypeError       

map_dict = {'int': call_integer, 'str': call_str}
my_function('12.7')
# str
Austin
  • 25,759
  • 4
  • 25
  • 48