Aahz wrote: > On Sun, Mar 15, 2009, Michael Foord wrote: > >> Aahz wrote: >> >>> On Sun, Mar 15, 2009, Michael Foord wrote: >>> >>>> >>>> Note that using exceptions for control flow can be bad for other >>>> implementations of Python. For example exceptions on the .NET >>>> framework are very expensive. (Although there are workarounds such >>>> as not really raising the exception - but they're ugly). >>>> >>>> Isn't it better practise for exceptions to be used for exceptional >>>> circumstances rather than for control flow? >>>> >>> It seems to me that we as a development community already made a decision >>> when we switched to StopIteration as the primary mechanism for halting >>> ``for`` loops. (Not that it was really a new decision because parts of >>> the Python community have always advocated using exceptions for control >>> flow, but the ``for`` loop enshrines it.) I doubt that using exceptions >>> for control flow in ``with`` blocks will cause anywhere near so much a >>> performance degradation. >>> >> >> Well, StopIteration is still an implementation detail that only >> occasionally bleeds through to actual programming. It says nothing >> about whether using exceptions for non-exceptional circumstances >> (control flow) is good practise. Personally I think it makes the >> intent of code less easy to understand - in effect the exceptions >> *are* being used as a goto. >> > > Let me know how you'd rewrite this more clearly without a control-flow > exception: > > try: > for field in curr_fields: > for item in record[field]: > item = item.lower() > for filter in excludes: > if match(item, filter): > raise Excluded > except Excluded: > continue > > This is pretty much the canonical example showing why control-flow > exceptions are a Good Thing. They're a *structured* goto. > You didn't include all the code - so impossible to match the exact semantics. Breaking out of multiple loops with a return is a cleaner way to handle it IMHO. def find_excludes(): for field in curr_fields: for item in record[field]: item = item.lower() for filter in excludes: if match(item, filter): return while something: find_excludes() Michael -- http://www.ironpythoninaction.com/ http://www.voidspace.org.uk/blog
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4