PEP 308: Alternative conditional operator forms

Steven Taschuk staschuk at telusplanet.net
Thu Feb 13 06:45:30 EST 2003


Quoth Michele Simionato:
  [on the PEP's (if c: x else: y) syntax]
> and I hate the next unavoidable step 
>
> (try: X except: Y)

Ultimately, of course, this slippery slope results in even
assignment statements becoming expressions, that is,
	(a = b)
would have some value.  Whatever its value, the feared bug
	if (a = b): # oops -- meant a == b
		...
would rise from the dead and haunt us anew.

I think it is safe to say that this eventuality will not arise
under our present BDFL (long may he rule).  That assignment
statements are not expressions is one of many instances in Python
in which a generalization has been avoided because it was felt to
have unacceptable consequences; imho this is Pythonic.  (For
another example, consider that we have lots of control-flow
keywords, but the generalization 'goto' is conspicuously missing.)
In other words, this particular slippery slope actually has lots
of traction.

That said, I kind of like the idea of (try: x except: y).

One simple application would be a list.find() method with the same
not-found behaviour as str.find():
	def find(self, x):
	    return (try: self.index(x) except ValueError: -1)

It might also be handy when producing HTML:
	>>> import codecs
	>>> encode = codecs.lookup('latin-1')[0]
	>>> entities = { u'\u2122': '™', ... }
	>>> output = ''
	>>> for char in u'Spam\u2122':
	...     output += (try: encode(char)[0]
	...         except UnicodeError: entities[char])
	...
	>>> print output
	Spam™
	>>>

Fwiw, I'm (if PEP308.accepted: +1 else: -1) on a PEP308-like
syntax for try-except.

-- 
Steven Taschuk           | import bisect, sys
staschuk at telusplanet.net | for line in sys.stdin: print ''.join([chr(ord(c)-13
                         | +bisect.bisect('\0AN[an{',c)%3*13) for c in line]),





More information about the Python-list mailing list