[Python-ideas] why not try without except?
spir
denis.spir at free.fr
Sat Apr 25 10:32:07 CEST 2009
Hello,
In various cases, we need to do something (set or update a var or attribute, launch an action, compute data), or not, according to a condition that is a potential case of exception.
Python provides the try...except construct to allow straightforward expression of the non-exceptional case without overloading the code with explicit checkings.
Still, in the common case above, the result is
try:
<do_something>
except ErrorType:
pass
or we have to fall back to a pre-checking construct
if not <error_case>:
<do_something>
For instance
try:
text += doc.footer
except ErrorType:
pass
or
if hasattr(doc, 'footer')
text += doc.footer
Actually, this shows that 'try' alone can be considered analog to 'if' without 'else' clause, needed when the condition may raise an exception. Both express an optional action. This could be written more directly, because we do not need the condition:
? <do_something>
option <do_something>
with the meaning: "Try & do this, but if there's an exception just let it down."
The same syntax may be reused in other contexts such as for having optional parameters:
def f(data, option param):
def f(data, ? param):
Actually, the meaning is the same: "Try & and read a second argument, but if you step on an exception just let it down." Moreover, the body of the func will probably use precisely the same construct to try and do something using the optional param, e.g.:
class Circle:
.......
def draw(self, ? fill_color):
<draw outline>
? self.fill(fill_color)
As a nice side-effect, this would also remove one of the common (mis?)uses of None -- which is often considered problematic because of conflicting various uses.
I would then support the introduction of such a syntax, or of 'try' without 'except'. And sincerally thank you for explaining why the latter was not allowed from start.
Denis
------
la vita e estrany
More information about the Python-ideas
mailing list