也许“种类” monad在Python中 [英] Maybe "kind-of" monad in Python

查看:63
本文介绍了也许“种类” monad在Python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



所以,在我的Python代码中有这样的东西:

company = None
country = None

person = Person.find(id = 12345)
如果人不是None:#found
company = Company.find(person.companyId)

如果公司不是None:
country = Country。 find(company.countryId)

return(person,company,country)

阅读了Haskell monads(特别是 Maybe )的教程后,我想知道是否可以用另一种方式编写它。

解决方案

company = country = None
try:
person = Person.find(id = 12345)
company = Company.find(person.companyId)
country = Country.find(company.countryId)
,但AttributeError:
pass#`person`或`company`可能是None

EAFP


Trying to find a way to clean up some of my code.

So, I have something like this in my Python code:

company = None
country = None

person = Person.find(id=12345)
if person is not None: # found        
    company = Company.find(person.companyId)

    if company is not None:
         country = Country.find(company.countryId)

return (person, company, country)

Having read a tutorial on Haskell's monads (in particular Maybe), I was wondering if it's possible to write it in another way.

解决方案

company = country = None
try:
    person  =  Person.find(id=12345)
    company = Company.find(person.companyId)
    country = Country.find(company.countryId)
except AttributeError:
    pass # `person` or `company` might be None

EAFP

这篇关于也许“种类” monad在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆