私はPythonを始めたばかりです。私は自分のアプリでキャッシュを多用していますが、私のコードにはこれと同じパターンがますます散らばっています。これは、ショップ全体で使用されている標準的なキャッシュ パターンです。このボイラープレートの一部を乾かすことができる Python のセクシーな構文トリックはありますか?
(ところで、これは実際のコードではありません)
# Determine if we are allowed to use cache
cacheable = settings.cache.lifetime is not None
# Generate unique cache key
cache_key = 'something_unique_{some_arg}'.format(some_arg=*args[0])
# Return cached version if allowed and available
if cacheable:
cached = memcache.get(cache_key)
if cached:
return cached
# Generate output
output = do_something_fooey(args[0])
# Cache output if allowed
if cacheable:
memcache.set(cache_key, output, settings.cache.lifetime)
return output
私もこれを突き刺すつもりです。おそらくキャッシュラッパー関数を作成し、出力生成を「デリゲート」としてそれに渡します(それがPython用語であるかどうかはわかりません)が、Pythonからアドバイスを得ることができれば素晴らしいでしょう専門家。