Debian Codegraph @

traits/examples/introduction/1_validation.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 Validation
13 ==========
14
15 A common issue faced by scientists is ensuring that the data that is
16 entered matches the sort of data that is expected. For example, we expect
17 that the filename is a string (or perhaps a pathlib **Path**, for advanced
18 users), the operator name is a string, the acquisition date is a
19 datetime.date object, and so on. Many languages allow (or even require)
20 you to specify these data types as part of your program, but even then these
21 data types tend to reflect what the computer stores in memory, and not what
22 the data actually *represents*.
23
24 For example, not only should the file be a string, but we would like to
25 validate that the string is in fact a valid path name, and ideally that the
26 file can actually be found. A sample ID may be expected to follow some pattern
27 based on lab protocols. The image data is expected to be a 2D array of values
28 rather than just any NumPy array. And so on.
29
30 Traits provides a way to ensure that values are validated when assigned in your
31 classes: as part of your class definition you _declare_ what you expect your
32 data to be. To do this, the first thing you want to do is inherit from the
33 base ``HasTraits`` class which enables all of the validation machinery::
34
35 from traits.api import HasTraits
36
37 class Image(HasTraits):
38 ''' An SEM image stored in a file. '''
39
40 Having done this, we can declare the types of data that we expect for the
41 attributes of an ``Image`` class. For example, we expect that the operator
42 name should be a string, so we can use the standard Traits ``Str`` trait
43 type::
44
45 from traits.api import HasTraits, Str
46
47 class Image(HasTraits):
48 ''' An SEM image stored in a file. '''
49
50 operator = Str()
51
52 Now, if we try and assign any other value to the ``operator`` attribute, we
53 find that the class will raise a ``TraitError``::
54
55 >>> image = Image()
56 >>> image.operator = 3
57 TraitError: The 'operator' trait of an Image instance must be a
58 string, but a value of 3 <class 'int'> was specified.
59
60 Traits has trait types corresponding to all the basic Python data types:
61 ``Int``, ``Float``, ``Complex``, ``Bool``, and ``Str``. It also has trait
62 types for the standard containers: ``List``, ``Dict``, ``Set`` and ``Tuple``.
63 There is an ``Instance`` trait type for values which are instances of a
64 Python class. Traits also provides a rich set of trait types that cover
65 many common data types, for example:
66
67 - we can use a ``Date`` trait type for the date_acquired
68 - we can specify that the scan size is not just a tuple, but a pair of
69 floating point values by specifying ``Tuple(Float, Float)``.
70 - we can use a ``File`` trait for the filename, and we can require that the
71 path refer to an existing file by using ``File(exists=True)``.
72 - we can specify that the image data is a 2D NumPy array of unsigned integers
73 with ``Array(shape=(None, None), dtype='uint8')``
74
75 Everything else can remain unchanged in the class, and it will still work as
76 expected, however just as with regular Python classes, we need to remember
77 to call ``super()`` in the ``__init__`` method::
78
79 def __init__(self, filename, sample_id, date_acquired, operator,
80 scan_size=(1e-5, 1e-5)):
81 super().__init__()
82
83 # initialize the primary attributes
84 ...
85
86 When we talk about an attribute which is declared by a trait type, it is
87 common to call it a _trait_ rather than an attribute.
88
89
90 Traits and Static Types
91 -----------------------
92
93 The first version of Traits was written over 15 years ago. In the last 5
94 years or so, Python has started to gain the ability to perform static type
95 checking using tools like MyPy and certain integrated development
96 environments. The ``dataclass`` module introduced in recent Python versions
97 can do similar sorts of type declaration for classes. Advanced Python users
98 may be aware of, and using these classes already.
99
100 As we will see, the capabilities of Traits are much greater than these type
101 checking systems, however if you have the traits-stubs package installed,
102 most of your trait type declarations will be recognised and can be used with
103 these new Python type systems.
104
105
106 Exercise
107 --------
108
109 The example code hasn't declared trait types for all the attributes used by
110 the class. Declare trait types for ``scan_width``, ``scan_height`` and
111 ``pixel_area``.
112
113 """
114
115 import datetime
116 import os
117
118 from traits.api import Array, Date, HasTraits, File, Float, Str, Tuple
119
120
121 class Image(HasTraits):
122 """ An SEM image stored in a file. """
123
124 filename = File(exists=True)
125
126 sample_id = Str()
127
128 date_acquired = Date()
129
130 operator = Str()
131
132 scan_size = Tuple(Float, Float)
133
134 image = Array(shape=(None, None), dtype='uint8')
135
136 def __init__(self, filename, sample_id, date_acquired, operator,
137 scan_size=(1e-5, 1e-5)):
138 super().__init__()
139
140 # initialize the primary attributes
141 self.filename = filename
142 self.sample_id = sample_id
143 self.scan_size = scan_size
144 self.operator = operator
145
146 # useful secondary attributes
147 self.scan_width, self.scan_height = self.scan_size
148
149
150 # ---------------------------------------------------------------------------
151 # Demo code
152 # ---------------------------------------------------------------------------
153
154 this_dir = os.path.dirname(__file__)
155 image_dir = os.path.join(this_dir, "images")
156 filename = os.path.join(image_dir, "sample_0001.png")
157
158 # load the image
159 image = Image(
160 filename=filename,
161 operator="Hannes",
162 sample_id="0001",
163 date_acquired=datetime.datetime.today(),
164 scan_size=(1e-5, 1e-5),
165 )
166
167 # show all the defined traits
168 image.print_traits()
169
170 # we can't set the operator name to a number
171 print(set)
172 try:
173 image.operator = 3
174 except Exception as exc:
175 print(exc)
176
177 # we can't create an image which uses a non-existent path
178 non_existent_filename = os.path.join(image_dir, "does_not_exist.png")
179
180 try:
181 image = Image(
182 filename=filename,
183 operator="Hannes",
184 sample_id="0001",
185 date_acquired=datetime.datetime.today(),
186 scan_size=(1e-5, 1e-5),
187 )
188 except Exception as exc:
189 print(exc)