cleaner way to write this?

Roy Smith roy at panix.com
Thu Oct 26 02:20:15 CEST 2006


In article <mailman.1218.1161819774.11739.python-list at python.org>,
 Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:

> John Salerno <johnjsal at NOSPAMgmail.com> writes:
> 
> >          if dlg.ShowModal() == wx.ID_OK:
> >              db_name = dlg.GetValue()
> >              dlg.Destroy()
> >              return db_name
> >          else:
> >              dlg.Destroy()
> >              return
> 
> It's for reasons like this that I prefer to have only one 'return'
> from my functions.
> 
>     db_name = None
>     if dlg.ShowModal() == wx.ID_OK:
>         db_name = dlg.GetValue()
>     dlg.Destroy()
>     return db_name

Isn't this the kind of thing that the new-fangled "with" statement is 
supposed to solve?

     def create_db_name(self):
         with  wx.TextEntryDialog(self.frame, 'Enter a database name:',
                                  'Create New Database') as dlg:
            if dlg.ShowModal() == wx.ID_OK:
                db_name = dlg.GetValue()
                return db_name
            else:
                return

or something like that.  The problem here is that it looks like dlg is 
expecting to have Destroy() called instead of just being destructed.  
Which, of course, is the problem that RAII is supposed to solve :-)



More information about the Python-list mailing list