ãã£ãã·ã¥ã¨å¹ç
Life is beautiful: Python Hack : 噛めば噛むほどおいしくなるクロージャの話ãè¦ã¦ãããããã¨æ°ã«ãªãã¨ããããã£ãã®ã§æ¸ãã¦ã¿ãã
import yaml def _get_from_disk(): data = open('config.yaml').read().decode('utf8') config = yaml.load(data)ãï¼ ã¯ãã¼ã¸ã£å ã«é è½ã»ä¿æããããã¼ã«ã«å¤æ° global get get = lambda : config # äºåç®ããã¯configãè¿ãç¡åé¢æ°ãå¼ã¶æ§ã«å¤æ´ return get() get = _get_from_disk # ååã®ã¿ãã¼ãã¼ãå®è¡http://satoshi.blogs.com/life/2009/11/python-hack.html
ééãã¾ããâ¦ããã®é¨åã¯ãã¡ãã¨åãã¦ã¾ããã
ã¾ããåç´ãªã³ã¼ãã£ã³ã°ãã¹ã®ãã¨ã
_get_from_disk
ãå¼ãã æç¹ã§getã«é¢æ°ãã»ãããããã®ã§ãgetã¸ã®ä»£å
¥ã¯å¿
è¦ãªãã
æ¨æ¸¬ã ãã_get_from_disk
ã¨ããé¢æ°ã¯æ¬å½ã¯get
ã¨ããååã§ãä¸åº¦å¼ã¶ã¨é¢æ°ããã£ãã·ã¥æ¸ã¿ã®configãè¿ãããã«å·®ãæ¿ããããã¨ããæåãããããã£ãã®ã ã¨æãã
ãããã¥ããã¨ããäºä»¥å¤ã®æ¬ ç¹ã«ã¤ãã¦è§¦ãããã¦ããªãã£ãã®ã§ãæãã¤ããã ãæããã
ã¾ããæ®éã®å®è£
import yaml _config = None def get(): global _config if not _config: data = open('config.yaml').read().decode('utf8') _config = yaml.load(data) return _confighttp://satoshi.blogs.com/life/2009/11/python-hack.html
ã§ã¯ã
ãããééãã§ãâ¦ã
æåã«getãå¼ã°ããã¿ã¤ãã³ã°ã§è¨å®ãã¡ã¤ã«ããã¼ããããããã¯ãã¼ã¸ã£ã使ã£ãã»ãã§ã¯ã³ã¼ããèªã¿è¾¼ã¾ããæç¹ã§configã«å¤ãæç¸ããã¦ãã¾ããããã¯ã¡ã¢ãªå¹çä¸ãããªãã
ã¾ããgetãå·®ãæ¿ããå®è£
ã ã¨ããã¨é«éé¢æ°ã¨ãã¦ã»ãã®é¢æ°ã«æ¸¡ãäºãã§ããªããªãããã®å ´åã ã¨åã«ä½åº¦ãloadãããã ãã ããå ´åã«ãã£ã¦ã¯ãã°ã®çºçæºã¨ãªããããã¡ã³ããã³ã¹æ§ã¯è½ã¡ãã
é度åä¸ã«å½¹ã«ç«ã¤ãã«ã¤ãã¦ãçåã«æãã
from time import time, strftime _i = None def a(): global _i if not _i: i = 0 return i def b(): i = 0 global b b = lambda : i return i v = 0 t = time() for i in xrange(1000000): a() v += i print time() - t t = time() for i in xrange(1000000): b() v += i print time() - t print v
ãã®ãããªã¹ã¯ãªãããèµ°ããããã
% python a.py 0.412140846252 0.377043008804 999999000000
ãã®ãããªçµæãå¾ãããã100ä¸åå¼ã³åºãã¦ãã£ãã®0.035msããé度ãå¤ãããªããªã¼ãããããã馬鹿ã«ãªããªã
ã»ã©ã§ãããã¨ã¯å°ãªãã¨æãã
ãã¦ãã°ãã¼ãã«å¤æ°ã®ä½¿ç¨ãé¿ãããã¤å¯èªæ§ãããã»ã©è½ã¡ãªãæ¸ãæ¹ãèãã¦ã¿ããã
ã¾ããé¢æ°ã®attributeã使ãæ¹æ³ã
def fn(): if not hasattr(fn, "__value"): fn.__value = "initialize" return fn.__value
å¤é¨ããã¢ã¯ã»ã¹ãããã¨æãã°ã§ãã¦ãã¾ãã®ãçã«çãhasattrã使ãã®ãå°ãè¦ã¥ããã
classãã¤ããæ¹æ³ã
class Fn(): def __init__(self): self.__value = "initialize" def __call__(self): return self.__value fn = Fn()
Fnã®åæåæã«ãã¡ã¤ã«åããªãã·ã§ã³ã¨ãã¦æ¸¡ããããã«ãããã§ããã®ã§ãæ¡å¼µæ§ã®é¢ã§ã¯åªãã¦ããã
ãã®ä»ã®æ¹æ³ã¨ãã¦ããªãã·ã§ã³å¼æ°ã®åæåãå®ç¾©ææåã®å¼ã³åºãæã«ããè¡ãããªããã¨ãå©ç¨ããã
def f(value="initialize"): return value
ãªã©ãããããã ãããã¯å°æ¥ã®ãã¼ã¸ã§ã³ã§ä½¿ãããã©ããããããªãããã¯ã§ããã
ãã®è©±ã§å¿ è¦ã¨ããã¦ããã®ã¯ã¯ãã¼ã¸ã£ã§ã¯ãªãstaticå¤æ°ã§ãããæ§ã ãªä»£æ¿æ段ãããã®ã§å¯èªæ§ã¨é度ã天秤ã«ããé©åãªæ段ãé¸ã¶ã¹ãã ã