-
Notifications
You must be signed in to change notification settings - Fork 6
/
sample.txt
79 lines (62 loc) · 1.83 KB
/
sample.txt
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
79
ObjectTemplates
================
ObjectTemplates are a template for creating objects. They work well with Factories.
A **Bunch** is simply a bunch of attributes. Keyword arguments to a Bunch are turned into attributes:
>>> b = Bunch(pants=42, shirt=15)
>>> b.pants
42
>>> b.shirt
15
Calling a bunch returns a new copy:
>>> c = b()
>>> c.__dict__ == b.__dict__
True
>>> c is b
False
When called, an **ObjectTemplate** instance produces a new instance
of ``bunchClass``. Attributes on the template are passed as kwargs
to the bunch. However, if an attribute is callable, it is called
and the return value is used instead:
>>> counter = itertools.count(1).next # an incrementing counter
>>> def color():
... return "blue"
>>> template = ObjectTemplate(size=42,
... color=color,
... count=counter,
... bunchClass=Bunch)
>>> bunch = template()
>>> isinstance(bunch, Bunch)
True
>>> bunch.size
42
>>> bunch.color
'blue'
>>> bunch.count
1
Each call to the template produces a new bunch. Any functions will
be called again:
>>> bunch2 = template()
>>> bunch2.count
2
If you want to pass a callable object to the bunch, wrap it in a lambda:
>>> template = ObjectTemplate()
>>> template.return_val = color
>>> template.a_function = lambda: color
>>> bunch = template()
>>> bunch.return_val
'blue'
>>> bunch.a_function #doctest:+ELLIPSIS
<function color at ...>
ObjectTemplate can be used for configuration::
config = ObjectTemplate()
# in production
config.path = "/var/myapp/"
config.debug_level = logging.WARN
# in tests
config.path = Factory(tempfile.mktemp)
config.debug_level = logging.DEBUG
# app code
def do_stuff_with_config(config):
config = config() # call any factories
output = file(config.path)
logging.setLevel(config.debug_level)