也许“有点"Python 中的 monad [英] Maybe "kind-of" monad in Python

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

问题描述

试图找到一种方法来清理我的一些代码.

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

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

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)

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

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

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

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