File: expression.py

package info (click to toggle)
python-traits 6.4.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,648 kB
  • sloc: python: 34,801; ansic: 4,266; makefile: 102
file content (565 lines) | stat: -rw-r--r-- 18,056 bytes parent folder | download
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!

import functools

from traits.observation._anytrait_filter import anytrait_filter
from traits.observation._dict_item_observer import DictItemObserver
from traits.observation._filtered_trait_observer import FilteredTraitObserver
from traits.observation._list_item_observer import ListItemObserver
from traits.observation._metadata_filter import MetadataFilter
from traits.observation._named_trait_observer import NamedTraitObserver
from traits.observation._observer_graph import ObserverGraph
from traits.observation._set_item_observer import SetItemObserver


#: Maximum number of parsed observer expressions stored in the LRU caches
_OBSERVER_EXPRESSION_CACHE_MAXSIZE = 256


# ObserverExpression is a public user interface for constructing ObserverGraph.

class ObserverExpression:
    """
    ObserverExpression is an object for describing what traits are being
    observed for change notifications. It can be passed directly to
    ``HasTraits.observe`` method or the ``observe`` decorator.

    An ObserverExpression is typically created using one of the top-level
    functions provided in this module, e.g. ``trait``.
    """

    __slots__ = ()

    def __or__(self, expression):
        """ Create a new expression that matches this expression OR
        the given expression.

        e.g. ``trait("age") | trait("number")`` will match either trait
        **age** or trait **number** on an object.

        Parameters
        ----------
        expression : ObserverExpression

        Returns
        -------
        new_expression : ObserverExpression
        """
        return ParallelObserverExpression(self, expression)

    def then(self, expression):
        """ Create a new expression by extending this expression with
        the given expression.

        e.g. ``trait("child").then( trait("age") | trait("number") )``
        on an object matches ``child.age`` or ``child.number`` on the object.

        Parameters
        ----------
        expression : ObserverExpression

        Returns
        -------
        new_expression : ObserverExpression
        """
        return SeriesObserverExpression(self, expression)

    def match(self, filter, notify=True):
        """ Create a new expression for observing traits using the
        given filter.

        Events emitted (if any) will be instances of
        :class:`~traits.observation.events.TraitChangeEvent`.

        Parameters
        ----------
        filter : callable(str, CTrait) -> bool
            A callable that receives the name of a trait and the corresponding
            trait definition. The returned bool indicates whether the trait
            is observed. In order to remove an existing observer with the
            equivalent filter, the filter callables must compare equally. The
            callable must also be hashable.
        notify : bool, optional
            Whether to notify for changes. Default is to notify.

        Returns
        -------
        new_expression : ObserverExpression
        """
        return self.then(match(filter=filter, notify=notify))

    def anytrait(self, notify=True):
        """ Create a new expression for observing all traits.

        Events emitted (if any) will be instances of
        :class:`~traits.observation.events.TraitChangeEvent`.

        Parameters
        ----------
        notify : bool, optional
            Whether to notify for changes. Default is to notify.

        Returns
        -------
        new_expression : ObserverExpression
        """
        return self.match(filter=anytrait_filter, notify=notify)

    def metadata(self, metadata_name, notify=True):
        """ Return a new expression for observing traits where the given
        metadata is not None.

        Events emitted (if any) will be instances of
        :class:`~traits.observation.events.TraitChangeEvent`.

        e.g. ``metadata("age")`` matches traits whose 'age' attribute has a
        non-None value.

        Parameters
        ----------
        metadata_name : str
            Name of the metadata to filter traits with.
        notify : bool, optional
            Whether to notify for changes. Default is to notify.

        Returns
        -------
        new_expression : ObserverExpression
        """
        return self.match(
            filter=MetadataFilter(metadata_name=metadata_name),
            notify=notify,
        )

    def dict_items(self, notify=True, optional=False):
        """ Create a new expression for observing items inside a dict.

        Events emitted (if any) will be instances of
        :class:`~traits.observation.events.DictChangeEvent`.

        If an expression with ``dict_items`` is further extended, the
        **values** of the dict will be given to the next item in the
        expression. For example, the following observes a trait named "number"
        on any object that is one of the values in the dict named "mapping"::

            trait("mapping").dict_items().trait("number")

        Parameters
        ----------
        notify : bool, optional
            Whether to notify for changes. Default is to notify.
        optional : bool, optional
            Whether to ignore this if the upstream object is not a dict.
            Default is false and an error will be raised if the object is not
            a dict.

        Returns
        -------
        new_expression : ObserverExpression
        """
        return self.then(dict_items(notify=notify, optional=optional))

    def list_items(self, notify=True, optional=False):
        """ Create a new expression for observing items inside a list.

        Events emitted (if any) will be instances of
        :class:`~traits.observation.events.ListChangeEvent`.

        e.g. ``trait("containers").list_items()`` for observing mutations
        to a list named ``containers``.

        e.g. ``trait("containers").list_items().trait("value")`` for observing
        the trait ``value`` on any items in the list ``containers``.

        Parameters
        ----------
        notify : bool, optional
            Whether to notify for changes. Default is to notify.
        optional : bool, optional
            Whether to ignore this if the upstream object is not a list.
            Default is false and an error will be raised if the object is not
            a list.

        Returns
        -------
        new_expression : ObserverExpression
        """
        return self.then(list_items(notify=notify, optional=optional))

    def set_items(self, notify=True, optional=False):
        """ Create a new expression for observing items inside a set.

        Events emitted (if any) will be instances of
        :class:`~traits.observation.events.SetChangeEvent`.

        Parameters
        ----------
        notify : bool, optional
            Whether to notify for changes. Default is to notify.
        optional : bool, optional
            Whether to ignore this if the upstream object is not a set.
            Default is false and an error will be raised if the object is not
            a set.

        Returns
        -------
        new_expression : ObserverExpression
        """
        return self.then(set_items(notify=notify, optional=optional))

    def trait(self, name, notify=True, optional=False):
        """ Create a new expression for observing a trait with the exact
        name given.

        Events emitted (if any) will be instances of
        :class:`~traits.observation.events.TraitChangeEvent`.

        Parameters
        ----------
        name : str
            Name of the trait to match.
        notify : bool, optional
            Whether to notify for changes. Default is to notify.
        optional : bool, optional
            If true, skip this observer if the requested trait is not found.
            Default is false, and an error will be raised if the requested
            trait is not found.

        Returns
        -------
        new_expression : ObserverExpression
        """
        return self.then(trait(name=name, notify=notify, optional=optional))

    def _as_graphs(self):
        """ Return all the ObserverGraph for the observer framework to attach
        notifiers.

        This is considered private to the users and to modules outside of the
        ``observation`` subpackage, but public to modules within the
        ``observation`` subpackage.

        Returns
        -------
        graphs : list of ObserverGraph
        """
        return self._create_graphs(branches=[])

    def _create_graphs(self, branches):
        """ Return a list of ObserverGraph with the given branches.

        Parameters
        ----------
        branches : list of ObserverGraph
            Graphs to be used as branches.

        Returns
        -------
        graphs : list of ObserverGraph
        """
        raise NotImplementedError("'_create_graphs' must be implemented.")


class SingleObserverExpression(ObserverExpression):
    """ Container of ObserverExpression for wrapping a single observer.
    """

    __slots__ = ("_observer",)

    def __init__(self, observer):
        self._observer = observer

    def __hash__(self):
        return hash((type(self).__name__, self._observer))

    def __eq__(self, other):
        return (
            type(self) is type(other)
            and self._observer == other._observer
        )

    def _create_graphs(self, branches):
        return [
            ObserverGraph(node=self._observer, children=branches),
        ]


class SeriesObserverExpression(ObserverExpression):
    """ Container of ObserverExpression for joining expressions in series.

    Parameters
    ----------
    first : ObserverExpression
        Left expression to be joined in series.
    second : ObserverExpression
        Right expression to be joined in series.
    """

    __slots__ = ("_first", "_second")

    def __init__(self, first, second):
        self._first = first
        self._second = second

    def __hash__(self):
        return hash((type(self).__name__, self._first, self._second))

    def __eq__(self, other):
        return (
            type(self) is type(other)
            and self._first == other._first
            and self._second == other._second
        )

    def _create_graphs(self, branches):
        branches = self._second._create_graphs(branches=branches)
        return self._first._create_graphs(branches=branches)


class ParallelObserverExpression(ObserverExpression):
    """ Container of ObserverExpression for joining expressions in parallel.

    Parameters
    ----------
    left : ObserverExpression
        Left expression to be joined in parallel.
    right : ObserverExpression
        Right expression to be joined in parallel.
    """

    __slots__ = ("_left", "_right")

    def __init__(self, left, right):
        self._left = left
        self._right = right

    def __hash__(self):
        return hash((type(self).__name__, self._left, self._right))

    def __eq__(self, other):
        return (
            type(self) is type(other)
            and self._left == other._left
            and self._right == other._right
        )

    def _create_graphs(self, branches):
        left_graphs = self._left._create_graphs(branches=branches)
        right_graphs = self._right._create_graphs(branches=branches)
        return left_graphs + right_graphs


def join(*expressions):
    """ Convenient function for joining many expressions in series
    using ``ObserverExpression.then``

    Parameters
    ----------
    *expressions : iterable of ObserverExpression

    Returns
    -------
    new_expression : ObserverExpression
        Joined expression.
    """
    return functools.reduce(lambda e1, e2: e1.then(e2), expressions)


def dict_items(notify=True, optional=False):
    """ Create a new expression for observing items inside a dict.

    Events emitted (if any) will be instances of
    :class:`~traits.observation.events.DictChangeEvent`.

    If an expression with ``dict_items`` is further extended, the
    **values** of the dict will be given to the next item in the expression.
    For example, the following observes a trait named "number" on any object
    that is one of the values in the dict named "mapping"::

        trait("mapping").dict_items().trait("number")

    Parameters
    ----------
    notify : bool, optional
        Whether to notify for changes. Default is to notify.
    optional : bool, optional
        Whether to ignore this if the upstream object is not a dict.
        Default is false and an error will be raised if the object is not
        a dict.

    Returns
    -------
    new_expression : ObserverExpression
    """
    observer = DictItemObserver(notify=notify, optional=optional)
    return SingleObserverExpression(observer)


def list_items(notify=True, optional=False):
    """ Create a new expression for observing items inside a list.

    Events emitted (if any) will be instances of
    :class:`~traits.observation.events.ListChangeEvent`.

    e.g. ``trait("containers").list_items()`` for observing mutations
    to a list named ``containers``.

    e.g. ``trait("containers").list_items().trait("value")`` for observing
    the trait ``value`` on any items in the list ``containers``.

    Parameters
    ----------
    notify : bool, optional
        Whether to notify for changes. Default is to notify.
    optional : bool, optional
        Whether to ignore this if the upstream object is not a list.
        Default is false and an error will be raised if the object is not
        a list.

    Returns
    -------
    new_expression : ObserverExpression
    """
    observer = ListItemObserver(notify=notify, optional=optional)
    return SingleObserverExpression(observer)


def match(filter, notify=True):
    """ Create a new expression for observing traits using the
    given filter.

    Events emitted (if any) will be instances of
    :class:`~traits.observation.events.TraitChangeEvent`.

    Parameters
    ----------
    filter : callable(str, CTrait) -> bool
        A callable that receives the name of a trait and the corresponding
        trait definition. The returned bool indicates whether the trait is
        observed. In order to remove an existing observer with the equivalent
        filter, the filter callables must compare equally. The callable must
        also be hashable.
    notify : bool, optional
        Whether to notify for changes.

    Returns
    -------
    new_expression : ObserverExpression
    """
    observer = FilteredTraitObserver(notify=notify, filter=filter)
    return SingleObserverExpression(observer)


def anytrait(notify=True):
    """ Create a new expression for observing all traits on an object.

    Events emitted (if any) will be instances of
    :class:`~traits.observation.events.TraitChangeEvent`.

    Parameters
    ----------
    notify : bool, optional
        Whether to notify for changes.
    """
    observer = FilteredTraitObserver(notify=notify, filter=anytrait_filter)
    return SingleObserverExpression(observer)


def metadata(metadata_name, notify=True):
    """ Return a new expression for observing traits where the given metadata
    is not None.

    Events emitted (if any) will be instances of
    :class:`~traits.observation.events.TraitChangeEvent`.

    e.g. ``metadata("age")`` matches traits whose 'age' attribute has a
    non-None value.

    Parameters
    ----------
    metadata_name : str
        Name of the metadata to filter traits with.
    notify : bool, optional
        Whether to notify for changes. Default is to notify.

    Returns
    -------
    new_expression : ObserverExpression
    """
    return match(
        filter=MetadataFilter(metadata_name=metadata_name),
        notify=notify,
    )


def set_items(notify=True, optional=False):
    """ Create a new expression for observing items inside a set.

    Events emitted (if any) will be instances of
    :class:`~traits.observation.events.SetChangeEvent`.

    Parameters
    ----------
    notify : bool, optional
        Whether to notify for changes. Default is to notify.
    optional : bool, optional
        Whether to ignore this if the upstream object is not a set.
        Default is false and an error will be raised if the object is not
        a set.

    Returns
    -------
    new_expression : ObserverExpression
    """
    observer = SetItemObserver(notify=notify, optional=optional)
    return SingleObserverExpression(observer)


def trait(name, notify=True, optional=False):
    """ Create a new expression for observing a trait with the exact
    name given.

    Events emitted (if any) will be instances of
    :class:`~traits.observation.events.TraitChangeEvent`.

    Parameters
    ----------
    name : str
        Name of the trait to match.
    notify : bool, optional
        Whether to notify for changes. Default is to notify.
    optional : bool, optional
        If true, skip this observer if the requested trait is not found.
        Default is false, and an error will be raised if the requested
        trait is not found.

    Returns
    -------
    new_expression : ObserverExpression
    """
    observer = NamedTraitObserver(
        name=name, notify=notify, optional=optional)
    return SingleObserverExpression(observer)


@functools.lru_cache(maxsize=_OBSERVER_EXPRESSION_CACHE_MAXSIZE)
def compile_expr(expr):
    """ Compile an ObserverExpression to a list of ObserverGraphs.

    Parameters
    ----------
    expr : ObserverExpression

    Returns
    -------
    list of ObserverGraph
    """
    return expr._as_graphs()