I made a function in my wxpython app that pop up a passwordbox. The code, that’s present in dialogs.py, looks like this:
def password_dialog(self, password):
# Only ask for password if it actually exist
if password == 'False':
return True
question = 'Put in password:'
dialog = wx.PasswordEntryDialog(self, question, 'Password...')
if dialog.ShowModal() == wx.ID_OK:
if dialog.GetValue() == password:
dialog.Destroy()
return True
else:
dialog.Destroy()
__wrong_pass()
raise WrongPassword
else:
dialog.Destroy()
raise CancelDialog
The exceptions is in the same file:
class WrongPassword(Exception):
pass
class CancelDialog(Exception):
pass
In my main program I then have some methods that look something like this:
def on_sort_songs(self, event):
"""Renumbering the database and sort in artist and title order"""
# Check for password first
try:
dialogs.password_dialog(self, opts.generic['password'])
except dialogs.CancelDialog:
return
except dialogs.WrongPassword:
return
# Sort database and repopulate GUI
self.jbox.sort_songs()
self.populate_songlist()
It work ok. But it don’t seems like a very good and pythonic way to handle password dialogs. Or is it?
I dont think your dialog function should be raising exceptions in this case. Just have it return True or False depending on whether the validation passes or not. Then all you need to do is:
Exceptions would only be necessary for other random failure cases that you want to distinguish, such as “Authentication Server is Down”
Another reason I think its good to return True or False in this case is because then you can use modular authentication methods that can be swapped out. Such as how django uses a single is_authenticated() method that returns a boolean. The end use only needs to worry about whether its authenticated or not. Not what various exceptions it raises specifically, like a dialog being closed. Some cases might not even use a dialog..maybe a command line, or a web interface ,etc.