Created
May 20, 2014 05:58
-
-
Save hachibeeDI/6f0d2340d1070244b829 to your computer and use it in GitHub Desktop.
Object#try in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import (print_function, division, absolute_import, unicode_literals, ) | |
from operator import methodcaller | |
class Perhaps(object): | |
''' | |
>>> p = Perhaps('hoge huga foo') | |
>>> P = p.try_('replace', 'huga', 'muoo').try_('upper').apply(print) | |
HOGE MUOO FOO | |
>>> p = Perhaps(None) | |
>>> p.try_('replace', 'huga', 'muoo').try_('upper').var is None | |
True | |
''' | |
def __init__(self, var): | |
self.var = var | |
def try_(self, methodname, *args, **kw): | |
v = self.var | |
if v is None: | |
return self | |
else: | |
self.var = methodcaller(methodname, *args, **kw)(v) | |
return self | |
def apply(self, func, *args, **kw): | |
v = self.var | |
if v is None: | |
return self | |
else: | |
self.var = func(self.var, *args, **kw) | |
return self | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment