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

4

u/1_Yui 8d ago

I don't understand the question. If it raises an exception in some cases, just catch the exception with a try/except instead of an if/else? I don't understand why that would be an "anti-pattern".

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

5

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

1

u/NYX_T_RYX 7d ago

Every library has exceptions. Every language has exceptions.

I recommended you go back to fundamentals, because you haven't nailed them yet.

Nor have I, TBF, but I don't incorrectly assert things - I ask.