Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maybe "kind-of" monad in Python

Tags:

python

haskell

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.

like image 823
Andriy Drozdyuk Avatar asked Dec 14 '11 15:12

Andriy Drozdyuk


People also ask

Is maybe a monad?

In FP we often loosely say things like "arrays are monads" or "maybe values are monadic" etc. However, speaking more strictly, it is not the values (like [1, 2, 3] , Nothing , or Just(6) ) that are monads, but the context (the Array or Maybe "namespace" as you put it).

What is monad in Python?

A monad is a design pattern that allows us to add a context to data values, and also allows us to easily compose existing functions so that they execute in a context aware manner.

What are the different classes of monads?

Common monadsNondeterminism using List monad to represent carrying multiple values. State using State monad. Read-only environment using Reader monad. I/O using IO monad.

Why is monad useful?

monads are used to address the more general problem of computations (involving state, input/output, backtracking, ...) returning values: they do not solve any input/output-problems directly but rather provide an elegant and flexible abstraction of many solutions to related problems.


2 Answers

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

like image 138
Katriel Avatar answered Oct 26 '22 23:10

Katriel


Exploit the short-circuit behavior and that a custom object is true by default and None is false:

person  = Person.find(id=12345) company = person and person.company country = company and company.country 
like image 44
jfs Avatar answered Oct 26 '22 23:10

jfs