On Learning Python, Part 2
February 18, 2007
# Bind the name getpass to the appropriate function try: import termios, TERMIOS except ImportError: try: import msvcrt except ImportError: try: from EasyDialogs import AskPassword except ImportError: getpass = default_getpass else: getpass = AskPassword else: getpass = win_getpass else: getpass = unix_getpass
Is this the generally accepted use of Exceptions and Exception Handling in Python? I mean, is it a good and proper thing to use Exception Handling for more than handling the truly exceptional behavior?
I have grown to understand that at least in the .NET world, it is best to catch exceptions that you can't anticipate happening, because if you could anticipate them happening you would code for those cases.
For example, instead of using the try/except (or try/catch) blocks, use if/else blocks testing for the different conditions one could anticipate and then perform the logic as necessary. This could very well lead to the use of a Strategy Pattern to keep things neat and easily extensible.
In the example above, instead of letting an Exception control the logic flow, you could determine what platform you are running on and based on that determination assign the proper function to getpass.
I believe this teaching largely stems from the notion that a try/catch is more expensive than logic tests. But furthermore, it allows for the leveraging of OO patterns like the Strategy Pattern.
Am I missing something here? Or is it just done differently in Python? Do the concepts I have learned so far in my software engineering career only marginally apply in these new world of Python? Or could it be that this single source of Python instruction is not the end-all-be-all of Python best practices?