2012年9月28日

[python] lookup local variable name by value

今天無意間看到一段超妙的 code
這實在太帥了 XD

忍不住立刻就應用到 error response :p

# response_maker.py

def generate_output(code=status_code.OK, params=None):
    if params is None:
        output = {'status': code}
    else:
        output = params
        if not 'status' in output:
            output['status'] = code
    if code is not status_code.OK:
        output['status_msg'] = status_code.description_by_val[code]
    return json.dumps(output)
# status_code.py

OK = 200
InvalidParam = 20000
ForbiddenAction = 20001
OpenDatabaseFail = 20002

from collections import Hashable
description_by_val = dict(
    (value, key) for key, value in locals().iteritems()
    if not key.startswith("__")
    and value
    and isinstance(value, Hashable)
)

沒有留言:

張貼留言