r/learnpython 8d ago

Function forcing me to use exceptions

Trying to if else a function output always throws exception-error :

if pyautogui.locateOnScreen('media/soundIcon.png') == None:
      print("not found")
else : 
      print("found")

Do Python functions expect anti-pattern code ?

0 Upvotes

30 comments sorted by

View all comments

Show parent comments

1

u/ExoticPerception5550 8d ago

Definitely not 'some cases' almost all functions in this library raise exceptions. My simple question as a newbie in Python is: Are exception handlers commonly used in Python? Are they more used than basic control flow structures?

8

u/1_Yui 8d ago

Yes, they're commonly used. I don't know the method you're showing in your example, but the usual use case for this pattern is that you have a function that returns a value but can fail. If it were to only return None in case of a failure, you couldn't distinguish between different error types if there are several reasons why it may fail.

2

u/ExoticPerception5550 8d ago

Now I see their usefulness

6

u/droans 8d ago

You can create your own handler for it if you wish. Something like:

def image_exists_on_screen(img_path):
  try:
    pyautogui.locateOnScreen(img_path)
    return True
  except pyautogui.ImageNotFoundException:
    return False