style query: function attributes for return codes?
holger krekel
hpk at trillke.net
Fri Dec 10 13:11:46 EST 2004
Hi George,
[george young Fri, Dec 10, 2004 at 10:45:47AM -0500]
> [python 2.3.3, x86 linux]
> I recently found myself writing something like:
>
> def get_connection():
> if tcp_conn():
> if server_allows_conn():
> return 'good_conn'
> else:
> return 'bad_auth'
> else:
> return 'no_server'
>
> cn = get_connection()
> if cn == 'good_con': ...
>
>
> This is obviously just evil, since a misspelling in the string
> return is treacherous.
Right.
I usually like to look at such problems from the angle of
what is most convenient for the *caller* side?
And having to adress function attributes does
not seem convenient. I'd probably like to do from
the caller side something like:
conn = get_connection()
if conn.good:
...
elif conn.badauth:
...
elif conn.noserver:
...
which allows you to freely choose and hide your actual
implementation at the "called" side. Example:
class Connection(object):
def __init__(self, **kw):
for name in kw:
assert name in ('good', 'badauth', 'noserver'), name
setattr(self, name, kw[name])
def get_connection():
if tcp_conn():
if server_allows_conn():
return Connection(good=True)
else:
return Connection(badauth=True)
else:
return Connection(noserver=True)
And btw, the view of "what do i want at the caller side?"
is natural if you do test-driven development and actually
first write your tests. Another reason why testing is
a good thing :-)
cheers & HTH,
holger
More information about the Python-list
mailing list