/
README
78 lines (47 loc) · 1.5 KB
/
README
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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