A better way for "except" and "return"?

Jason Orendorff jason at jorendorff.com
Fri Jan 4 12:27:22 EST 2002


> The whole thing works. I was wondering though. [...]

If you want tons of annoying advice, you came to the right place!

* You don't need to handle exceptions at the exact point they occur.
  This makes for ugly, redundant code.  In fact, you don't need
  any error-handling code within this function.  The exceptions
  will propagate upwards to the caller automatically.  Catch any
  exceptions there.

* Maybe you really don't need to return any information from this
  method.  Instead, have it return quietly on success, and raise
  an exception if it fails.  (You can have it print a debug message
  if it succeeds, too.)

* "cursor" is spelled with an "o".

* The function you posted returns before the last 2 lines ever
  get executed.  This means db.commit() never runs.  Intentional?

* Use """triple-quotes""" for docstrings, even if they fit all on
  one line.  And, of course, make sure your docstrings are accurate.

Bottom line - your code could be just half as long, if you use
exceptions the way they're intended to work.

    def add(self, user, password, group):
        """Add a user to ICRADIUS.  Raise ValueError if user exists."""

        validUser, db, cursor = self._isUser(user)
        if validUser is not None:
            raise ValueError("User " + user + " already exists.  " +
                             "Try another user name.")

        cursor.execute("""INSERT INTO radcheck (UserName, Attribute, Value)
                              VALUES (%s, %s, %s)""",
                       (user, 'Password', password))
        cursor.execute("""INSERT INTO usergroup (UserName, GroupName)
                              VALUES (%s, %s)""", (user, group))
        db.commit()
        cursor.close()

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list