エラー/ステータスコード検索用の静的変数を持つクラスがあります。例として HTTP ステータス コードを取り上げます。
class Foo(object):
OK = 200
Not_Modified = 304
Forbidden = 403
Internal_Server_Error = 500
ここで、コード (200、403 など) に基づいて口頭のステータス ('OK'、'Not_Modified' など) を取得する必要があります。他のプログラムが使用しているため、クラスの構造を変更できません。そこで、以下description_by_val
を含む辞書を作成しました{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'
今、パフォーマンスとコードの練習に関して質問があります。
- 呼び出すたびに
Foo.description_by_val
、辞書が再生成されますか? これは、データセットが非常に小さい場合でも、何百万回も呼び出されるため、良くありません。 - それは単に悪い習慣にアプローチするのですか?手動で辞書を手動で作成したくないので、静的変数にする必要があると思います。
何か考えはありますか?
アップデート:
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'
パフォーマンスについて心配する必要がないことに満足しています。なぜこのように振る舞うかを知りたい:)