I have a class with static variables to search for error / status code. Take the HTTP status code as an example
class Foo(object):
OK = 200
Not_Modified = 304
Forbidden = 403
Internal_Server_Error = 500
Now I need to get the verbal status ('OK', 'Not_Modified', etc.) based on the code (200, 403, etc.). I cannot change the structure of the class, as other programs use it. So I created a dictionary description_by_valcontaining {code : description}:
from collections import Hashable
class Foo(object):
OK = 200
Not_Modified = 304
Forbidden = 403
Internal_Server_Error = 500
description_by_val = dict((value, key)
for key, value in locals().iteritems()
if not key.startswith("__") and value and isinstance(value, Hashable))
>>> Foo.description_by_val[200]
'OK'
Now I have questions in terms of code performance and practice.
- Every time I call
Foo.description_by_val, it will lead to a dictionary regeneration? this is bad, even the data set is very small, because it will cause millions of times. - , ? , , .
?
:
, - description_by_val, , .
>>> from collections import Hashable
>>>
>>> def show(key):
... print key
... return True
...
>>>
>>> class Foo(object):
... OK = 200
... Not_Modified = 304
... Forbidden = 403
... Internal_Server_Error = 500
... description_by_val = dict((value, key)
... for key, value in locals().iteritems()
... if not key.startswith("__") and key and isinstance(value, Hashable) and show(key))
...
OK
Forbidden
Internal_Server_Error
Not_Modified
>>>
>>> Foo.description_by_val
{200: 'OK', 304: 'Not_Modified', 403: 'Forbidden', 500: 'Internal_Server_Error'}
>>> Foo.description_by_val
{200: 'OK', 304: 'Not_Modified', 403: 'Forbidden', 500: 'Internal_Server_Error'}
>>> Foo.description_by_val[200]
'OK'
, . , :)