Debian Codegraph @

envisage/service.py

raw
1 # (C) Copyright 2007-2025 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 """ A trait type used to access services. """
11
12
13 # Standard library imports.
14 import logging
15
16 # Enthought library imports.
17 from traits.api import TraitError, TraitType
18
19 # Logging.
20 logger = logging.getLogger(__name__)
21
22
23 class Service(TraitType):
24 """A trait type used to access services.
25
26 Note that this is a trait *type* and hence does *NOT* have traits itself
27 (i.e. it does *not* inherit from 'HasTraits').
28
29 """
30
31 ###########################################################################
32 # 'object' interface.
33 ###########################################################################
34
35 def __init__(
36 self, protocol=None, query="", minimize="", maximize="", **metadata
37 ):
38 """Constructor."""
39
40 super().__init__(**metadata)
41
42 # The protocol that the service must provide.
43 self._protocol = protocol
44
45 # The optional query.
46 self._query = query
47
48 # The optional name of the trait/property to minimize.
49 self._minimize = minimize
50
51 # The optional name of the trait/property to maximize.
52 self._maximize = maximize
53
54 def __repr__(self):
55 """String representation of a Service object"""
56 return "Service(protocol={!r})".format(self._protocol)
57
58 ###########################################################################
59 # 'TraitType' interface.
60 ###########################################################################
61
62 def get(self, obj, trait_name):
63 """Trait type getter."""
64
65 service_registry = self._get_service_registry(obj)
66
67 obj = service_registry.get_service(
68 self._protocol, self._query, self._minimize, self._maximize
69 )
70
71 return obj
72
73 def set(self, obj, name, value):
74 """Trait type setter."""
75
76 raise TraitError("Service traits cannot be set")
77
78 ###########################################################################
79 # Private interface.
80 ###########################################################################
81
82 def _get_service_registry(self, obj):
83 """Return the service registry in effect for an object."""
84
85 service_registry = getattr(obj, "service_registry", None)
86 if service_registry is None:
87 raise ValueError(
88 'The "Service" trait type can only be used within objects '
89 "that have a reference to a service registry via their "
90 '"service_registry" trait. \n'
91 "Object %s\nService protocol %s" % (obj, self._protocol)
92 )
93
94 return service_registry