0

I have a function name "is_target_line(line)", this function is validate each line that I read in the txt file, and I am thinking what is the best practice to raise the Error.

def is_target_line(line:str):
    if 'specific_string' in line:
        return True
    else:
        return False

Python will not check if line is str or not, so I will add a logic to raise the error like this.

def is_target_line(line:str):
    if type(line) != str:
        raise TypeError
    if 'specific_string' in line:
        return True
    else:
        return False

My question is, should I add this logic control to raise the Error for checking type, or just let the python interpreter to raise the Error in run time, and what is the good practice of throwing error ?

EnergyBoy
  • 547
  • 1
  • 5
  • 18
  • 2
    FWIW: `return 'specific_string' in line`. `if ...: return True else: return False` is basically always overly verbose and redundant. – deceze May 27 '21 at 09:58
  • You can use a `try: ` `except TypeError: ` block to handle the type error. It's a common practice in Python, see [here](https://stackoverflow.com/a/16138864/6352008). – Plopp May 27 '21 at 10:02

0 Answers0