具有合并函数和“magic”空值的简单python库
Coalesce的Python项目详细描述
具有合并函数和“magic”空值的简单python库 其他功能
安装
pip install coalesce
功能
唯一值
这是一个包含一些抽象唯一值的工厂
示例:
fromcoalesceimportUniqueValueYes=UniqueValue(truthful=True)MayBe=UniqueValue()IDontKnow=UniqueValue()Unlikely=UniqueValue()No=UniqueValue(truthful=False)defanswer_lottery():importrandomreturnrandom.choice((Yes,MayBe,IDontKnow,Unlikely,No))print("- Are you hungry?")hungry_answer=answer_lottery()try:ifhungry_answer:print("- YES, i would eat an elephant!")else:print("- I'm fed up...")exceptTypeError:print("- Well, I want only coffee")print("- Will you marry me?")marry_answer=answer_lottery()ifmarry_answer==Yes:print("- Well, finally, YES!")elifmarry_answer==MayBe:print("- Well, only if you really are rich...")elifmarry_answer==IDontKnow:print("- I need to think...")elifmarry_answer==Unlikely:print("- When the cancer on the mountain whistles.")elifmarry_answer==No:print("- Who are you, boy?")
空
empty是conrete错误的唯一值。
在情况下使用,当我们想要不同的无和真正的“空”值。 例如,设置动态计算的默认值:
fromcoalesceimportemptyfromrandomimportrandintdeff(value=empty):ifvalue==empty:value=randint(1,10)print('value={}'.format(value))f()# value=<random(1,10)>f(None)# value=None
合并
函数首先返回不忽略来自iterable对象的值。由 默认忽略empty值
示例:
fromcoalesceimportcoalesce,emptyfromrandomimportrandintdeff(value=empty):value=coalesce([value,randint(1,10)])print('value={}'.format(value))f()# value=<random(1,10)>f(None)# value=Noneprintcoalesce([None,1,2],ignore=None,default=-7)# 1printcoalesce([None,None],ignore=None,default=-7)# -7
第一个
函数返回iterable中的第一个值 function(value)来自iterable对象。否则它会回来 默认值
示例:
fromcoalesceimportfirstprintfirst(lambdax:x>1,[None,1,2],default=-7)# 2printfirst(lambdax:x>2,[None,1,2],default=-7)# -7