style query: function attributes for return codes?

Steven Bethard steven.bethard at gmail.com
Fri Dec 10 18:54:08 CET 2004


Robert Kern wrote:
> Steven Bethard wrote:
> 
>> Sorry, I also meant to add that the other obvious way of dealing with 
>> this kind of thing is to make the results keyword parameters:
>>
>> def get_connection(GOOD=1, BAD_AUTH=2, NO_SERVER=3):
>>     if tcp_conn():
>>         if server_allows_conn():
>>             return GOOD
>>         else:
>>             return BAD_AUTH
>>     else:
>>         return NO_SERVER
>>
>> This has the benefit that if your user wants different return values 
>> they can specify them, but the disadvantage that someone improperly 
>> calling the function with more than 0 parameters will get, instead of 
>> an error message, a strange return value.
> 
> 
> Another disadvantage is that one must compare the return value by value 
> and not by name. That is, I cannot do something like this:
> 
> code = get_connection()
> if code == NO_SERVER:
>     ...

Good point.  The class-type implementation does allow you to do this:

 >>> class get_connection(object):
...     GOOD = 1
...     BAD_AUTH = 2
...     NO_SERVER = 3
...     def __new__(cls):
...         if tcp_conn():
...             if server_allows_conn():
...                 return cls.GOOD
...             else:
...                 return cls.BAD_AUTH
...         else:
...             return cls.NO_SERVER
...
 >>> get_connection.GOOD
1
 >>> get_connection.BAD_AUTH
2
 >>> get_connection.NO_SERVER
3

Steve



More information about the Python-list mailing list