1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2014
    Rep Power

    Pythonic way of writing error strings

    Total python newbie here...

    My goal is to call a function that returns an error code so that the caller can optionally print the associated error code string.

    Something like this in c++:

    typedef enum errorCodes
     errorCodes_Success = 0,
     errorCodes_Invalid = -1,
     errorCodes_BadDevice = -2
    } errorCodes;

    My first thought was to do a class that has a single array/list of (variable length) strings, that would be indexed into. But I've also read about Tuples, Dictionary, Deques, but these are new keywords for me so not sure what path to start down.

    Finally, I was thinking that using exceptions might be overkill (especially with lbyl vs eafp considerations)... but since I want to develop good idiomatic Python habits from the start, I'm open to any suggestions on what the typical way of reporting error strings / exception handling.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Joensuu, Finland
    Rep Power
    Actually, I think exceptions are a good and “Pythonic” way of doing that, especially in the internal levels of a program: a function would return either a sensible value or raise an exception instead of using a special return value in case of error as in some languages. It’s easy enough to create custom exceptions if the standard ones won’t fit semantically.

    On the user interface level one has to think again, especially if localizability should be considered. Personally I’m always having trouble on this level, sometimes using program-level error codes (constant integers named like E_CANTREAD) which can be fed directly to sys.exit() and outputted to the user using a error message dictionary, say:

    errors = {E_CANTREAD: "can't read file '{0}'",
              # …
    My armada: Debian GNU/Linux 8 (desktop, home laptop, work laptop), Raspbian GNU/Linux 8 (nameserver), Ubuntu 14.04.3 LTS (HTPC), PC-BSD 10.2 (testbed), Android 4.2.1 (tablet)

IMN logo majestic logo threadwatch logo seochat tools logo