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

Lewis Bergman lbergman at abi.tconline.net
Fri Jan 4 16:30:42 CET 2002


This is part of my first python program. It is a function that adds user's to 
a db. It is typical of many functions in the same class. All the functions 
use the same try, except Error, else, and close setup.

The whole thing works. I was wondering though. Can some of you with (what 
seems like decades from watching the list) of experience suggest a couple of 
ways to make the code tighter or easier to maintain? Any suggestions about 
other things I have forgotten are welcome as well.


	def add(self, user, password, group):
		"Add a user to ICRADIUS, 0 on success."

		validUser, db, curser = self._isUser(user)

		if validUser == None:
			try:
				curser.execute("""INSERT INTO radcheck (UserName, Attribute, Value)
								VALUES (%s, %s, %s)""",(user, 'Password', password,))
			except Error, (errno, strerror):
				err = "MySQL error(%s): %s" % (errno, strerror)
				return err
			try:
				curser.execute("""INSERT INTO usergroup (UserName, GroupName)
								VALUES (%s, %s)""",(user, group,))
			except Error, (errno, strerror):
				err = "MySQL error(%s): %s" % (errno, strerror)
				return err
			else:
				msg = 'User', user, 'added to system'
				r = {'exitCode':0, 'exitMessage':msg}
			return r
		else:
			msg = 'User', user, 'already exists. Try another user name'
			r = {'exitCode':1, 'exitMessage':msg}
			return r

		db.commit()
		curser.close()

Thanks for your time.
-- 
Lewis Bergman
Texas Communications
4309 Maple St.
Abilene, TX 79602-8044
915-695-6962 ext 115




More information about the Python-list mailing list