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

    Join Date
    Aug 2014
    Posts
    1
    Rep Power
    0

    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++:

    Code:
    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
    Location
    Joensuu, Finland
    Posts
    439
    Rep Power
    67
    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:

    Code:
    errors = {E_CANTREAD: "can't read file '{0}'",
              # …
             }
    My armada: openSUSE 13.2 (home desktop, work desktop), openSUSE 13.1 (home laptop), Debian GNU/Linux 7.7.0 (mini laptop), Ubuntu 14.04 LTS (server), Android 4.2.1 (tablet), Windows 7 Ultimate (testbed)

IMN logo majestic logo threadwatch logo seochat tools logo