Skip to content

royaltm/Maybe-Null

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Usage:

from maybe import Maybe

Maybe(someobj).someproperty.somemethod()

returns NullType() instead of raising AttributeError if someobj is None

opts = {'person': 'Very important person'}

len(Maybe(opts).get('person'))
21

from maybe import NullType
len(Maybe(Maybe(opts).get('robot')))
0

len(Maybe(opts).get('robot', NullType(None)))
0

opts = None

len(Maybe(opts).get('robot'))

0


Testing against None.

1. by equality and identity:
from maybe import Value

someobj = None

Value(Maybe(someobj)) is None
True

Maybe(someobj) == None
True


2. by instance check

from maybe import NullType
someobj = None

isinstance(Maybe(someobj), NullType)
True

isinstance(someobj, NullType)
True


Maybe as iterable:

Let's assume that `user` is an instance of User object that have `products` collection.
We want first product that satisfies `is_valid` criteria, however `user` may be None
or may not have any product satisfying our criteria:

Normally we would write something like this:

product = None
if user:
  valid_products = [p for p in user.products if p.is_valid]
  if valid_products:
    product = valid_products[0]

with Maybe we can shorten it to:

product = Maybe([p for p in Maybe(user).products if p.is_valid] or None)[0]



Inspired by:
- Avdi Grimm: http://avdi.org/devblog/2011/05/30/null-objects-and-falsiness/
- herenowcoder's not-none: https://github.com/herenowcoder/not_none
and
- raganwald's andand https://github.com/raganwald/andand

About

Maybe (NullType) class in python (poor man's maybe monad)

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages