george young wrote:
[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. I'm considering function attributes:

def get_connection():
    if tcp_conn():
        if server_allows_conn():
            return get_connection.GOOD
        else:
            return get_connection.BAD_AUTH
    else:
        return get_connection.NO_SERVER
get_connection.GOOD = 1
get_connection.BAD_AUTH = 2
get_connection.NO_SERVER = 3


If I put this function in it's own module, the solution is obvious:

GOOD_CONN = 1
def get_connection():
...
return GOOD_CONN



But if this is a small utility function that belongs inside a larger module/class, I would like to have it's return values closely associated with the function, not just another value in the parent class.

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.

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to