Preamble
One of the concepts used in writing Python code is "Easier to ask for forgiveness than permission", aka EAFP. Literally, this means that instead of doing checks, whether an operation is possible, you do the operation and "ask forgiveness" if what you do fails. Technically this means (just an example with no particular meaning):
try:
obj.x = 10
obj.y = 20
except AttributeError:
pass
This technique is often used when the code in try ... except
block is known to run without any errors in most cases, or if the code is rarely executed. The same code with preliminary checks would look as follows:
if hasattr(obj, 'x'):
obj.x = 10
if hasattr(obj, 'y'):
obj.y = 20
C++ practices
While generally not an issue in Python, C++ has a "heritage" flame war of "function returning error status" vs. "throwing exceptions". This has been discussed a lot, but I can't find any good source of information which describes whether the Python-like EAFP is applicable in Python.
E.g. consider the following:
if (node.has_element('x')) {
node['x'] = 10;
}
versus
try {
node['x'] = 10;
}
catch(ElementNotFoundException e) {
// pass
}
Which approach is generally used in C++ code? If performance is not the issue, would you write EAFP-fashioned code? Thank you.
node
is a map, the usual C++ code would be simply:node['x'] = 20
, and no exception would be possible.