I\'m not asking for personal \"religious\" opinions about this philosophy, rather something a bit more technical.
I understand this phrase is one of several litmus t
The classical "ask forgiveness not permission" example is accessing values from a dict
that may not exist. E.g.:
names = { 'joe': 'Joe Nathan', 'jo': 'Jo Mama', 'joy': 'Joy Full' }
name = 'hikaru'
try:
print names[name]
except KeyError:
print "Sorry, don't know this '{}' person".format(name)
Here the exception that might occur (KeyError
) is stated, so that you're not asking forgiveness for every error that might occur, but only the one that would naturally occur.
For comparison, the "ask permission first" approach might look like:
if name in names:
print names[name]
else:
print "Sorry, don't know this '{}' person".format(name)
or
real_name = names.get(name, None)
if real_name:
print real_name
else:
print "Sorry, don't know this '{}' person".format(name)
Such examples of "ask forgiveness" are often too simple. IMO it's not crystal clear that try
/except
blocks are inherently better than if
/else
. The real value is much clearer when performing operations that might fail in a variety of ways--such as parsing; using eval()
; accessing operating system, middleware, database, or network resources; or performing complex mathematics. When there are multiple potential failure modes, being prepared to get forgiveness is hugely valuable.
Other notes about your code examples:
You do not need to ladle try
/except
blocks around every variable usage. That would be horrible. And you don't need to set self.bar
in your __init__()
since it's set in your class
definition above. It is usual to define it either in the class (if it's data likely to be shared among all instances of the class) or in the __init__()
(if it's instance data, specific to each instance).
A value of None
is not undefined, or an error, by the way. It's a specific and legitimate value, meaning none, nil, null, or nothing. Many languages have such values so programmers don't "overload" 0
, -1
, ''
(empty string) or similar useful values.