-2

Instead using if/else to test a variable or function , using try/exception like described bellow would be more pythonic?

def fufu(oi):
    try:
        int(oi)
    except:
        raise
    else:
        return True

some_var = 1
try:
    some_var
except NameError:
    print("some_far not defined, boo hoo")
else:
    try:
        fufu(some_var)
    except:
        print("i'm not a guitarr, so i don't accept string,")
    else:
        print("Thank you for the integer: {}".format(some_var))
    finally:
        print("we're done")
finally:
    print("test finished")
thclpr
  • 4,945
  • 7
  • 39
  • 79
  • 1
    No, that code is not Pythonic. `fufu` seems pretty pointless, you're using bare `except`s and you're making assumptions you shouldn't (*whatever* goes wrong in `fufu` it must be because the argument was a string?) What are you *actually* trying to achieve? – jonrsharpe Jul 09 '15 at 12:59
  • @jonrsharpe now fufu tests int/string, the code is just an example about if i can use try/except instead of if/else to test results.... plus, the code was just an example to ask if i could use try/exept instead of if/else to test results. – thclpr Jul 09 '15 at 13:00
  • what do you mean *"test results"*? I certainly wouldn't write unit tests like that - use e.g. [`unittest.assertRaises`](https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises). And there's absolutely no point to the `except: raise` in `fufu`. – jonrsharpe Jul 09 '15 at 13:03
  • probably not really a duplicate, but if...else vs try...except is convered pretty well in [this answer](http://stackoverflow.com/a/7604717/238310). – Martijn Arts Jul 09 '15 at 13:07
  • @jonrsharpe damn.. it's frustrating not having english as a primary language... because i'm really struggling to try to explain my question. i'll update the question for a more basic example. – thclpr Jul 09 '15 at 13:16

1 Answers1

1

No, using try/except statements instead of if/else conditional statements to test a condition is not Pythonic.


PEP 8 and PEP 20 are the touchstones for what is considered "Pythonic". PEP 20 states:

Simple is better than complex.

[...]

Readability counts.

It would generally be agreed that conditional statements are simpler, more readable, and the expected way to test a condition in your code.

Community
  • 1
  • 1
jmlane
  • 1,961
  • 1
  • 15
  • 24