Debian Codegraph @

examples/tutorials/introduction/2_initialization.py

raw
1 # (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
2 # All rights reserved.
3 #
4 # This software is provided without warranty under the terms of the BSD
5 # license included in LICENSE.txt and may be redistributed only under
6 # the conditions described in the aforementioned license. The license
7 # is also available online at http://www.enthought.com/licenses/BSD.txt
8 #
9 # Thanks for using Enthought open source!
10
11 """
12 Initialization
13 ==============
14
15 If you have done any significant amount of object-oriented Python
16 programming, you may have noticed that your ``__init__`` methods often
17 have a lot of boilerplate. In our original example, the code copies all of
18 the ``__init__`` arguments to corresponding attributes before doing any
19 real work::
20
21 def __init__(self, filename, sample_id, date_acquired, operator,
22 scan_size=(1e-5, 1e-5)):
23 # initialize the primary attributes
24 self.filename = filename
25 self.sample_id = sample_id
26 self.operator = operator
27 self.scan_size = scan_size
28
29 Traits lets you avoid this boilerplate by defining a default ``__init__``
30 method that accepts keyword arguments that correspond to the declared
31 traits. The Traits version of the ``Image`` class could potentially skip
32 the ``__init__`` method entirely::
33
34 class Image(HasTraits):
35 filename = File(exists=True)
36 sample_id = Str()
37 date_acquired = Date()
38 operator = Str()
39 scan_size = Tuple(Float, Float)
40
41
42 # this works!
43 image = Image(
44 filename=filename,
45 operator="Hannes",
46 sample_id="0001",
47 date_acquired=datetime.datetime.today(),
48 scan_size=(1e-5, 1e-5),
49 )
50
51 Default Values
52 --------------
53
54 There are a couple of complications in the example that we need to take into
55 account. The first is what happens if a user forgets to provide an initial
56 value::
57
58 >>> image = Image(
59 ... filename=filename,
60 ... sample_id="0001",
61 ... date_acquired=datetime.datetime.today(),
62 ... scan_size=(1e-5, 1e-5),
63 ... )
64 >>> image.operator
65 ""
66
67 As this example shows, the operator gets given a default value of the empty
68 string ``""``. In fact every trait type comes with an default value. For
69 numeric trait types, like ``Int`` and ``Float``, the default is 0. For
70 ``Str`` trait types it is the empty string, for ``Bool`` traits it is
71 ``False``, and so on.
72
73 However, that might not be what you want as your default value. For example,
74 you might want to instead flag that the operator has not been provided with
75 the string ``"N/A"`` for "not available". Most trait types allow you to
76 specify a default value as part of the declaration. So we could say::
77
78 operator = Str("N/A")
79
80 and now if we omit ``operator`` from the arguments, we get::
81
82 >>> image.operator
83 "N/A"
84
85
86 Dynamic Defaults
87 ----------------
88
89 The second complication comes from more complex initial values. For example,
90 we could declare some arbitrary fixed date as the default value for
91 ``date_acquired``::
92
93 date_acquired = Date(datetime.date(2020, 1, 1))
94
95 But it would be better if we could set it to a dynamic value. For example,
96 a reasonable default would be today's date. You can provide this sort of
97 dynamically declared default by using a specially-named method which has
98 the pattern ``_<trait-name>_default`` and which returns the default value.
99 So we could write::
100
101 def _date_acquired_default(self):
102 return datetime.datetime.today()
103
104 Dynamic defaults are best used for values which don't depend on other traits.
105 For example, it might be tempting to have the ``image`` trait have a dynamic
106 default which loads in the data. As we will see, this is almost always
107 better handled by Traits observation and/or properties, which are discussed
108 in subsequent sections of the tutorial.
109
110
111 The ``traits_init`` Method
112 --------------------------
113
114 Although you aren't required to write an ``__init__`` method in a
115 ``HasTraits`` subclass, you can always choose to do so. If you do, you
116 **must** call ``super()`` to ensure that Traits has a chance to set up
117 its machinery. In our example the ``__init__`` method is also used to set
118 up some auxiliary values. This doesn't have to change::
119
120 def __init__(self, **traits):
121 super().__init__(**traits)
122
123 # useful secondary attributes
124 self.scan_width, self.scan_height = self.scan_size
125
126 However Traits offers a slightlty more convenient way of doing this sort of
127 post-initialization setup of state: you can define a ``traits_init`` method
128 which the ``HasTraits`` class ensures is called as part of the main
129 initialization process. When it has been called, all initial values will
130 have been set::
131
132 def traits_init(self):
133 # useful secondary attributes
134 self.scan_width, self.scan_height = self.scan_size
135
136
137 Exercise
138 --------
139
140 In our original example, the ``scan_size`` atribute had a default value of
141 ``(1e-5, 1e-5)``. Modify the code in the example so that the trait is
142 initialized to this default using a dynamic default method.
143
144 """
145
146
147 import datetime
148 import os
149
150 from traits.api import Array, Date, HasTraits, File, Float, Str, Tuple
151
152
153 class Image(HasTraits):
154 """ An SEM image stored in a file. """
155
156 filename = File(exists=True)
157
158 sample_id = Str()
159
160 date_acquired = Date()
161
162 operator = Str("N/A")
163
164 scan_size = Tuple(Float, Float)
165
166 image = Array(shape=(None, None), dtype='uint8')
167
168 def traits_init(self):
169 # useful secondary attributes
170 self.scan_width, self.scan_height = self.scan_size
171
172 def _date_acquired_default(self):
173 return datetime.datetime.today()
174
175
176 # ---------------------------------------------------------------------------
177 # Demo code
178 # ---------------------------------------------------------------------------
179
180 this_dir = os.path.dirname(__file__)
181 image_dir = os.path.join(this_dir, "images")
182 filename = os.path.join(image_dir, "sample_0001.png")
183
184 # load the image
185 image = Image(
186 filename=filename,
187 sample_id="0001",
188 scan_size=(1e-5, 1e-5),
189 )
190
191 # show all the defined traits
192 image.print_traits()