style query: function attributes for return codes?
Reinhold Birkenfeld
reinhold-birkenfeld-nospam at wolke7.net
Fri Dec 10 14:42:10 EST 2004
holger krekel wrote:
> 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)
That's evil, because "if conn.good" raises an AttributeError instead of
evaluating to False if the connection is not good. You would have to
inizialize all three attributes in every construction of a Connection
object.
Reinhold
--
[Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer
jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen
jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs-
mitteln inkompatibel. -- Florian Diesch in dcoulm
More information about the Python-list
mailing list