Home > database >  Should I make code conditional if fallacy of condition would make code unreachable
Should I make code conditional if fallacy of condition would make code unreachable

Time:01-06

suppose I have the following code:

def isIn(a:str, b:list[str]) -> str:
   yup = False
   for i in b:
      if i == a:
         return 'is'
         yup = True
   if not yup:
      return 'is not'

now, if line 7 is reached, yup must be false. According to the official Python style (perhaps PEP 8?), should I still make line 8 conditional, or should I just put it after the for statement?

CodePudding user response:

You don't even need yup. You either return from inside the loop, or the loop completes and you return 'is not'.

def isIn(a:str, b:list[str]) -> str:
   for i in b:
      if i == a:
         return 'is'
   return 'is not'

But all you are doing is reimplementing the in operator:

def isIn(a: str, b: list[str]) -> str:
    return 'is' if a in b else 'is not'

CodePudding user response:

This really has very little to do with PEP8, but just with programming logic.

In your code, since you return a value before even setting yup to True, yup will always be False in your entire function. So, checking if it is False is superfluous. In fact, this does the exact same:

def is_in(a: str, b: list[str]) -> str:
    for i in b:
        if i == a:
            return 'is'
    return 'is not'

Something that is a PEP8 issue is that you were using different indent depths, please don't. Also, whitespace is expected after the colon following a function parameter before the type hint. And naming functions and variables, you should stay away from capitals - isIn is OK but is_in is more Pythonic.

Note that your function as it currently is, only restricts an operator that Python has already (in that your type hints will cause warnings if the types don't match):

# this is how you'd use your function:
if is_in('word', ['a', 'word', 'or', 'four']) == 'is':
    print('it is')

# but you could just:
if 'word' in ['a', 'word', 'or', 'four']:
    print('it is')
  •  Tags:  
  • Related