-
-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathparameterized.py
More file actions
4537 lines (3830 loc) · 173 KB
/
parameterized.py
File metadata and controls
4537 lines (3830 loc) · 173 KB
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Generic support for objects with full-featured Parameters and
messaging.
This file comes from the Param library (https://github.com/holoviz/param)
but can be taken out of the param module and used on its own if desired,
either alone (providing basic Parameter support) or with param's
__init__.py (providing specialized Parameter types).
"""
import asyncio
import copy
import datetime as dt
import html
import inspect
import logging
import numbers
import operator
import random
import re
import types
import typing
import warnings
# Allow this file to be used standalone if desired, albeit without JSON serialization
try:
from . import serializer
except ImportError:
serializer = None
from collections import defaultdict, namedtuple, OrderedDict
from functools import partial, wraps, reduce
from html import escape
from itertools import chain
from operator import itemgetter, attrgetter
from types import FunctionType, MethodType
from contextlib import contextmanager
from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL
from ._utils import (
DEFAULT_SIGNATURE,
ParamDeprecationWarning as _ParamDeprecationWarning,
ParamFutureWarning as _ParamFutureWarning,
_deprecated,
_deprecate_positional_args,
_dict_update,
_in_ipython,
_is_auto_name,
_is_mutable_container,
_recursive_repr,
_validate_error_prefix,
accept_arguments,
iscoroutinefunction,
descendents,
)
# Ideally setting param_pager would be in __init__.py but param_pager is
# needed on import to create the Parameterized class, so it'd need to precede
# importing parameterized.py in __init__.py which would be a little weird.
if _in_ipython():
# In case the optional ipython module is unavailable
try:
from .ipython import ParamPager
param_pager = ParamPager(metaclass=True) # Generates param description
except ImportError:
param_pager = None
else:
param_pager = None
from inspect import getfullargspec
dt_types = (dt.datetime, dt.date)
_int_types = (int,)
try:
import numpy as np
dt_types = dt_types + (np.datetime64,)
_int_types = _int_types + (np.integer,)
except:
pass
VERBOSE = INFO - 1
logging.addLevelName(VERBOSE, "VERBOSE")
# Get the appropriate logging.Logger instance. If `logger` is None, a
# logger named `"param"` will be instantiated. If `name` is set, a descendant
# logger with the name ``"param.<name>"`` is returned (or
# ``logger.name + ".<name>"``)
logger = None
def get_logger(name=None):
if logger is None:
root_logger = logging.getLogger('param')
if not root_logger.handlers:
root_logger.setLevel(logging.INFO)
formatter = logging.Formatter(
fmt='%(levelname)s:%(name)s: %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
root_logger.addHandler(handler)
else:
root_logger = logger
if name is None:
return root_logger
else:
return logging.getLogger(root_logger.name + '.' + name)
# Indicates whether warnings should be raised as errors, stopping
# processing.
warnings_as_exceptions = False
docstring_signature = True # Add signature to class docstrings
docstring_describe_params = True # Add parameter description to class
# docstrings (requires ipython module)
object_count = 0
warning_count = 0
# Hook to apply to depends and bind arguments to turn them into valid parameters
_reference_transforms = []
def register_reference_transform(transform):
"""
Appends a transform to extract potential parameter dependencies
from an object.
Arguments
---------
transform: Callable[Any, Any]
"""
return _reference_transforms.append(transform)
def transform_reference(arg):
"""
Applies transforms to turn objects which should be treated like
a parameter reference into a valid reference that can be resolved
by Param. This is useful for adding handling for depending on objects
that are not simple Parameters or functions with dependency
definitions.
"""
for transform in _reference_transforms:
if isinstance(arg, Parameter) or hasattr(arg, '_dinfo'):
break
arg = transform(arg)
return arg
def eval_function_with_deps(function):
"""Evaluates a function after resolving its dependencies.
Calls and returns a function after resolving any dependencies
stored on the _dinfo attribute and passing the resolved values
as arguments.
"""
args, kwargs = (), {}
if hasattr(function, '_dinfo'):
arg_deps = function._dinfo['dependencies']
kw_deps = function._dinfo.get('kw', {})
if kw_deps or any(isinstance(d, Parameter) for d in arg_deps):
args = (getattr(dep.owner, dep.name) for dep in arg_deps)
kwargs = {n: getattr(dep.owner, dep.name) for n, dep in kw_deps.items()}
return function(*args, **kwargs)
def resolve_value(value):
"""
Resolves the current value of a dynamic reference.
"""
if isinstance(value, (list, tuple)):
return type(value)(resolve_value(v) for v in value)
elif isinstance(value, dict):
return type(value)((resolve_value(k), resolve_value(v)) for k, v in value.items())
elif isinstance(value, slice):
return slice(
resolve_value(value.start),
resolve_value(value.stop),
resolve_value(value.step)
)
value = transform_reference(value)
if hasattr(value, '_dinfo') or iscoroutinefunction(value):
value = eval_function_with_deps(value)
elif isinstance(value, Parameter):
value = getattr(value.owner, value.name)
return value
def resolve_ref(reference, recursive=False):
"""
Resolves all parameters a dynamic reference depends on.
"""
if recursive:
if isinstance(reference, (list, tuple, set)):
return [r for v in reference for r in resolve_ref(v)]
elif isinstance(reference, dict):
return [r for kv in reference.items() for o in kv for r in resolve_ref(o)]
elif isinstance(reference, slice):
return [r for v in (reference.start, reference.stop, reference.step) for r in resolve_ref(v)]
reference = transform_reference(reference)
if hasattr(reference, '_dinfo'):
dinfo = getattr(reference, '_dinfo', {})
args = list(dinfo.get('dependencies', []))
kwargs = list(dinfo.get('kw', {}).values())
refs = []
for arg in (args + kwargs):
if isinstance(arg, str):
owner = get_method_owner(reference)
if arg in owner.param:
arg = owner.param[arg]
elif '.' in arg:
path = arg.split('.')
arg = owner
for attr in path[:-1]:
arg = getattr(arg, attr)
arg = arg.param[path[-1]]
else:
arg = getattr(owner, arg)
refs.extend(resolve_ref(arg))
return refs
elif isinstance(reference, Parameter):
return [reference]
return []
def _identity_hook(obj, val):
"""To be removed when set_hook is removed"""
return val
class _Undefined:
"""
Dummy value to signal completely undefined values rather than
simple None values.
"""
def __bool__(self):
# Haven't defined whether Undefined is falsy or truthy,
# so to avoid subtle bugs raise an error when it
# is used in a comparison without `is`.
raise RuntimeError('Use `is` to compare Undefined')
def __repr__(self):
return '<Undefined>'
Undefined = _Undefined()
@contextmanager
def logging_level(level):
"""
Temporarily modify param's logging level.
"""
level = level.upper()
levels = [DEBUG, INFO, WARNING, ERROR, CRITICAL, VERBOSE]
level_names = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'VERBOSE']
if level not in level_names:
raise Exception(f"Level {level!r} not in {levels!r}")
param_logger = get_logger()
logging_level = param_logger.getEffectiveLevel()
param_logger.setLevel(levels[level_names.index(level)])
try:
yield None
finally:
param_logger.setLevel(logging_level)
@contextmanager
def _batch_call_watchers(parameterized, enable=True, run=True):
"""
Internal version of batch_call_watchers, adding control over queueing and running.
Only actually batches events if enable=True; otherwise a no-op. Only actually
calls the accumulated watchers on exit if run=True; otherwise they remain queued.
"""
BATCH_WATCH = parameterized.param._BATCH_WATCH
parameterized.param._BATCH_WATCH = enable or parameterized.param._BATCH_WATCH
try:
yield
finally:
parameterized.param._BATCH_WATCH = BATCH_WATCH
if run and not BATCH_WATCH:
parameterized.param._batch_call_watchers()
# PARAM3_DEPRECATION
@_deprecated(extra_msg="Use instead `batch_call_watchers`.")
@contextmanager
def batch_watch(parameterized, enable=True, run=True):
with _batch_call_watchers(parameterized, enable, run):
yield
@contextmanager
def batch_call_watchers(parameterized):
"""
Context manager to batch events to provide to Watchers on a
parameterized object. This context manager queues any events
triggered by setting a parameter on the supplied parameterized
object, saving them up to dispatch them all at once when the
context manager exits.
"""
BATCH_WATCH = parameterized.param._BATCH_WATCH
parameterized.param._BATCH_WATCH = True
try:
yield
finally:
parameterized.param._BATCH_WATCH = BATCH_WATCH
if not BATCH_WATCH:
parameterized.param._batch_call_watchers()
@contextmanager
def _syncing(parameterized, parameters):
old = parameterized._param__private.syncing
parameterized._param__private.syncing = set(old) | set(parameters)
try:
yield
finally:
parameterized._param__private.syncing = old
@contextmanager
def edit_constant(parameterized):
"""
Temporarily set parameters on Parameterized object to constant=False
to allow editing them.
"""
params = parameterized.param.objects('existing').values()
constants = [p.constant for p in params]
for p in params:
p.constant = False
try:
yield
except:
raise
finally:
for (p, const) in zip(params, constants):
p.constant = const
@contextmanager
def discard_events(parameterized):
"""
Context manager that discards any events within its scope
triggered on the supplied parameterized object.
"""
batch_watch = parameterized.param._BATCH_WATCH
parameterized.param._BATCH_WATCH = True
watchers, events = (list(parameterized.param._state_watchers),
list(parameterized.param._events))
try:
yield
except:
raise
finally:
parameterized.param._BATCH_WATCH = batch_watch
parameterized.param._state_watchers = watchers
parameterized.param._events = events
# External components can register an async executor which will run
# async functions
async_executor = None
def classlist(class_):
"""
Return a list of the class hierarchy above (and including) the given class.
Same as `inspect.getmro(class_)[::-1]`
"""
return inspect.getmro(class_)[::-1]
def get_all_slots(class_):
"""
Return a list of slot names for slots defined in `class_` and its
superclasses.
"""
# A subclass's __slots__ attribute does not contain slots defined
# in its superclass (the superclass' __slots__ end up as
# attributes of the subclass).
all_slots = []
parent_param_classes = [c for c in classlist(class_)[1::]]
for c in parent_param_classes:
if hasattr(c,'__slots__'):
all_slots+=c.__slots__
return all_slots
def get_occupied_slots(instance):
"""
Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.)
"""
return [slot for slot in get_all_slots(type(instance))
if hasattr(instance,slot)]
# PARAM3_DEPRECATION
@_deprecated()
def all_equal(arg1,arg2):
"""
Return a single boolean for arg1==arg2, even for numpy arrays
using element-wise comparison.
Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.
If both objects have an '_infinitely_iterable' attribute, they are
not be zipped together and are compared directly instead.
"""
if all(hasattr(el, '_infinitely_iterable') for el in [arg1,arg2]):
return arg1==arg2
try:
return all(a1 == a2 for a1, a2 in zip(arg1, arg2))
except TypeError:
return arg1==arg2
# PARAM3_DEPRECATION
# The syntax to use a metaclass changed incompatibly between 2 and
# 3. The add_metaclass() class decorator below creates a class using a
# specified metaclass in a way that works on both 2 and 3. For 3, can
# remove this decorator and specify metaclasses in a simpler way
# (https://docs.python.org/3/reference/datamodel.html#customizing-class-creation)
#
# Code from six (https://bitbucket.org/gutworth/six; version 1.4.1).
@_deprecated()
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass.
.. deprecated:: 2.0.0
"""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
for slots_var in orig_vars.get('__slots__', ()):
orig_vars.pop(slots_var)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
class bothmethod:
"""
'optional @classmethod'
A decorator that allows a method to receive either the class
object (if called on the class) or the instance object
(if called on the instance) as its first argument.
"""
def __init__(self, method):
self.method = method
def __get__(self, instance, owner):
if instance is None:
# Class call
return self.method.__get__(owner)
else:
# Instance call
return self.method.__get__(instance, owner)
def _getattrr(obj, attr, *args):
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return reduce(_getattr, [obj] + attr.split('.'))
def no_instance_params(cls):
"""
Disables instance parameters on the class
"""
cls._param__private.disable_instance_params = True
return cls
def _instantiate_param_obj(paramobj, owner=None):
"""Return a Parameter object suitable for instantiation given the class's Parameter object"""
# Shallow-copy Parameter object without the watchers
p = copy.copy(paramobj)
p.owner = owner
# Reset watchers since class parameter watcher should not execute
# on instance parameters
p.watchers = {}
# shallow-copy any mutable slot values other than the actual default
for s in p.__class__._all_slots_:
v = getattr(p, s)
if _is_mutable_container(v) and s != "default":
setattr(p, s, copy.copy(v))
return p
def _instantiated_parameter(parameterized, param):
"""
Given a Parameterized object and one of its class Parameter objects,
return the appropriate Parameter object for this instance, instantiating
it if need be.
"""
if (getattr(parameterized._param__private, 'initialized', False) and param.per_instance and
not getattr(type(parameterized)._param__private, 'disable_instance_params', False)):
key = param.name
if key not in parameterized._param__private.params:
parameterized._param__private.params[key] = _instantiate_param_obj(param, parameterized)
param = parameterized._param__private.params[key]
return param
def instance_descriptor(f):
# If parameter has an instance Parameter, delegate setting
def _f(self, obj, val):
# obj is None when the metaclass is setting
if obj is not None:
instance_param = obj._param__private.params.get(self.name)
if instance_param is None:
instance_param = _instantiated_parameter(obj, self)
if instance_param is not None and self is not instance_param:
instance_param.__set__(obj, val)
return
return f(self, obj, val)
return _f
def get_method_owner(method):
"""
Gets the instance that owns the supplied method
"""
if not inspect.ismethod(method):
return None
if isinstance(method, partial):
method = method.func
return method.__self__
# PARAM3_DEPRECATION
def recursive_repr(fillvalue='...'):
"""
Decorator to make a repr function return fillvalue for a recursive call
.. deprecated:: 1.12.0
"""
warnings.warn(
'recursive_repr has been deprecated and will be removed in a future version.',
category=_ParamDeprecationWarning,
stacklevel=2,
)
return _recursive_repr(fillvalue=fillvalue)
@accept_arguments
def output(func, *output, **kw):
"""
output allows annotating a method on a Parameterized class to
declare that it returns an output of a specific type. The outputs
of a Parameterized class can be queried using the
Parameterized.param.outputs method. By default the output will
inherit the method name but a custom name can be declared by
expressing the Parameter type using a keyword argument.
The simplest declaration simply declares the method returns an
object without any type guarantees, e.g.:
@output()
If a specific parameter type is specified this is a declaration
that the method will return a value of that type, e.g.:
@output(param.Number())
To override the default name of the output the type may be declared
as a keyword argument, e.g.:
@output(custom_name=param.Number())
Multiple outputs may be declared using keywords mapping from output name
to the type or using tuples of the same format, i.e. these two declarations
are equivalent:
@output(number=param.Number(), string=param.String())
@output(('number', param.Number()), ('string', param.String()))
output also accepts Python object types which will be upgraded to
a ClassSelector, e.g.:
@output(int)
"""
if output:
outputs = []
for i, out in enumerate(output):
i = i if len(output) > 1 else None
if isinstance(out, tuple) and len(out) == 2 and isinstance(out[0], str):
outputs.append(out+(i,))
elif isinstance(out, str):
outputs.append((out, Parameter(), i))
else:
outputs.append((None, out, i))
elif kw:
# (requires keywords to be kept ordered, which was not true in previous versions)
outputs = [(name, otype, i if len(kw) > 1 else None)
for i, (name, otype) in enumerate(kw.items())]
else:
outputs = [(None, Parameter(), None)]
names, processed = [], []
for name, otype, i in outputs:
if isinstance(otype, type):
if issubclass(otype, Parameter):
otype = otype()
else:
from .import ClassSelector
otype = ClassSelector(class_=otype)
elif isinstance(otype, tuple) and all(isinstance(t, type) for t in otype):
from .import ClassSelector
otype = ClassSelector(class_=otype)
if not isinstance(otype, Parameter):
raise ValueError('output type must be declared with a Parameter class, '
'instance or a Python object type.')
processed.append((name, otype, i))
names.append(name)
if len(set(names)) != len(names):
raise ValueError('When declaring multiple outputs each value '
'must be unique.')
_dinfo = getattr(func, '_dinfo', {})
_dinfo.update({'outputs': processed})
@wraps(func)
def _output(*args,**kw):
return func(*args,**kw)
_output._dinfo = _dinfo
return _output
def _parse_dependency_spec(spec):
"""
Parses param.depends specifications into three components:
1. The dotted path to the sub-object
2. The attribute being depended on, i.e. either a parameter or method
3. The parameter attribute being depended on
"""
assert spec.count(":")<=1
spec = spec.strip()
m = re.match("(?P<path>[^:]*):?(?P<what>.*)", spec)
what = m.group('what')
path = "."+m.group('path')
m = re.match(r"(?P<obj>.*)(\.)(?P<attr>.*)", path)
obj = m.group('obj')
attr = m.group("attr")
return obj or None, attr, what or 'value'
def _params_depended_on(minfo, dynamic=True, intermediate=True):
"""
Resolves dependencies declared on a Parameterized method.
Dynamic dependencies, i.e. dependencies on sub-objects which may
or may not yet be available, are only resolved if dynamic=True.
By default intermediate dependencies, i.e. dependencies on the
path to a sub-object are returned. For example for a dependency
on 'a.b.c' dependencies on 'a' and 'b' are returned as long as
intermediate=True.
Returns lists of concrete dependencies on available parameters
and dynamic dependencies specifications which have to resolved
if the referenced sub-objects are defined.
"""
deps, dynamic_deps = [], []
dinfo = getattr(minfo.method, "_dinfo", {})
for d in dinfo.get('dependencies', list(minfo.cls.param)):
ddeps, ddynamic_deps = (minfo.cls if minfo.inst is None else minfo.inst).param._spec_to_obj(d, dynamic, intermediate)
dynamic_deps += ddynamic_deps
for dep in ddeps:
if isinstance(dep, PInfo):
deps.append(dep)
else:
method_deps, method_dynamic_deps = _params_depended_on(dep, dynamic, intermediate)
deps += method_deps
dynamic_deps += method_dynamic_deps
return deps, dynamic_deps
def _resolve_mcs_deps(obj, resolved, dynamic, intermediate=True):
"""
Resolves constant and dynamic parameter dependencies previously
obtained using the _params_depended_on function. Existing resolved
dependencies are updated with a supplied parameter instance while
dynamic dependencies are resolved if possible.
"""
dependencies = []
for dep in resolved:
if not issubclass(type(obj), dep.cls):
dependencies.append(dep)
continue
inst = obj if dep.inst is None else dep.inst
dep = PInfo(inst=inst, cls=dep.cls, name=dep.name,
pobj=inst.param[dep.name], what=dep.what)
dependencies.append(dep)
for dep in dynamic:
subresolved, _ = obj.param._spec_to_obj(dep.spec, intermediate=intermediate)
for subdep in subresolved:
if isinstance(subdep, PInfo):
dependencies.append(subdep)
else:
dependencies += _params_depended_on(subdep, intermediate=intermediate)[0]
return dependencies
def _skip_event(*events, **kwargs):
"""
Checks whether a subobject event should be skipped.
Returns True if all the values on the new subobject
match the values on the previous subobject.
"""
what = kwargs.get('what', 'value')
changed = kwargs.get('changed')
if changed is None:
return False
for e in events:
for p in changed:
if what == 'value':
old = Undefined if e.old is None else _getattrr(e.old, p, None)
new = Undefined if e.new is None else _getattrr(e.new, p, None)
else:
old = Undefined if e.old is None else _getattrr(e.old.param[p], what, None)
new = Undefined if e.new is None else _getattrr(e.new.param[p], what, None)
if not Comparator.is_equal(old, new):
return False
return True
def extract_dependencies(function):
"""
Extract references from a method or function that declares the references.
"""
subparameters = list(function._dinfo['dependencies'])+list(function._dinfo['kw'].values())
params = []
for p in subparameters:
if isinstance(p, str):
owner = get_method_owner(function)
*subps, p = p.split('.')
for subp in subps:
owner = getattr(owner, subp, None)
if owner is None:
raise ValueError('Cannot depend on undefined sub-parameter {p!r}.')
if p in owner.param:
pobj = owner.param[p]
if pobj not in params:
params.append(pobj)
else:
for sp in extract_dependencies(getattr(owner, p)):
if sp not in params:
params.append(sp)
elif p not in params:
params.append(p)
return params
# Two callers at the module top level to support pickling.
async def _async_caller(*events, what='value', changed=None, callback=None, function=None):
if callback:
callback(*events)
if not _skip_event or not _skip_event(*events, what=what, changed=changed):
await function()
def _sync_caller(*events, what='value', changed=None, callback=None, function=None):
if callback:
callback(*events)
if not _skip_event(*events, what=what, changed=changed):
return function()
def _m_caller(self, method_name, what='value', changed=None, callback=None):
"""
Wraps a method call adding support for scheduling a callback
before it is executed and skipping events if a subobject has
changed but its values have not.
"""
function = getattr(self, method_name)
_caller = _async_caller if iscoroutinefunction(function) else _sync_caller
caller = partial(_caller, what=what, changed=changed, callback=callback, function=function)
caller._watcher_name = method_name
return caller
def _add_doc(obj, docstring):
"""Add a docstring to a namedtuple"""
obj.__doc__ = docstring
PInfo = namedtuple("PInfo", "inst cls name pobj what")
_add_doc(PInfo,
"""
Object describing something being watched about a Parameter.
`inst`: Parameterized instance owning the Parameter, or None
`cls`: Parameterized class owning the Parameter
`name`: Name of the Parameter being watched
`pobj`: Parameter object being watched
`what`: What is being watched on the Parameter (either 'value' or a slot name)
""")
MInfo = namedtuple("MInfo", "inst cls name method")
_add_doc(MInfo,
"""
Object describing a Parameterized method being watched.
`inst`: Parameterized instance owning the method, or None
`cls`: Parameterized class owning the method
`name`: Name of the method being watched
`method`: bound method of the object being watched
""")
DInfo = namedtuple("DInfo", "spec")
_add_doc(DInfo,
"""
Object describing dynamic dependencies.
`spec`: Dependency specification to resolve
""")
Event = namedtuple("Event", "what name obj cls old new type")
_add_doc(Event,
"""
Object representing an event that triggers a Watcher.
`what`: What is being watched on the Parameter (either value or a slot name)
`name`: Name of the Parameter that was set or triggered
`obj`: Parameterized instance owning the watched Parameter, or None
`cls`: Parameterized class owning the watched Parameter
`old`: Previous value of the item being watched
`new`: New value of the item being watched
`type`: `triggered` if this event was triggered explicitly), `changed` if
the item was set and watching for `onlychanged`, `set` if the item was set,
or None if type not yet known
""")
_Watcher = namedtuple("Watcher", "inst cls fn mode onlychanged parameter_names what queued precedence")
class Watcher(_Watcher):
"""
Object declaring a callback function to invoke when an Event is
triggered on a watched item.
`inst`: Parameterized instance owning the watched Parameter, or
None
`cls`: Parameterized class owning the watched Parameter
`fn`: Callback function to invoke when triggered by a watched
Parameter
`mode`: 'args' for param.watch (call `fn` with PInfo object
positional args), or 'kwargs' for param.watch_values (call `fn`
with <param_name>:<new_value> keywords)
`onlychanged`: If True, only trigger for actual changes, not
setting to the current value
`parameter_names`: List of Parameters to watch, by name
`what`: What to watch on the Parameters (either 'value' or a slot
name)
`queued`: Immediately invoke callbacks triggered during processing
of an Event (if False), or queue them up for processing
later, after this event has been handled (if True)
`precedence`: A numeric value which determines the precedence of
the watcher. Lower precedence values are executed
with higher priority.
"""
def __new__(cls_, *args, **kwargs):
"""
Allows creating Watcher without explicit precedence value.
"""
values = dict(zip(cls_._fields, args))
values.update(kwargs)
if 'precedence' not in values:
values['precedence'] = 0
return super().__new__(cls_, **values)
def __str__(self):
cls = type(self)
attrs = ', '.join([f'{f}={getattr(self, f)!r}' for f in cls._fields])
return f"{cls.__name__}({attrs})"
class ParameterMetaclass(type):
"""
Metaclass allowing control over creation of Parameter classes.
"""
def __new__(mcs, classname, bases, classdict):
# store the class's docstring in __classdoc
if '__doc__' in classdict:
classdict['__classdoc']=classdict['__doc__']
# when asking for help on Parameter *object*, return the doc slot
classdict['__doc__'] = property(attrgetter('doc'))
# Compute all slots in order, using a dict later turned into a list
# as it's the fastest way to get an ordered set in Python
all_slots = {}
for bcls in set(chain(*(base.__mro__[::-1] for base in bases))):
all_slots.update(dict.fromkeys(getattr(bcls, '__slots__', [])))
# To get the benefit of slots, subclasses must themselves define
# __slots__, whether or not they define attributes not present in
# the base Parameter class. That's because a subclass will have
# a __dict__ unless it also defines __slots__.
if '__slots__' not in classdict:
classdict['__slots__'] = []
else:
all_slots.update(dict.fromkeys(classdict['__slots__']))
classdict['_all_slots_'] = list(all_slots)
# No special handling for a __dict__ slot; should there be?
return type.__new__(mcs, classname, bases, classdict)
def __getattribute__(mcs,name):
if name=='__doc__':
# when asking for help on Parameter *class*, return the
# stored class docstring
return type.__getattribute__(mcs,'__classdoc')
else:
return type.__getattribute__(mcs,name)
class _ParameterBase(metaclass=ParameterMetaclass):
"""
Base Parameter class used to dynamically update the signature of all
the Parameters.
"""
@classmethod
def _modified_slots_defaults(cls):
defaults = cls._slot_defaults.copy()
defaults['label'] = defaults.pop('_label')
return defaults
@classmethod
def __init_subclass__(cls):
# _update_signature has been tested against the Parameters available
# in Param, we don't want to break the Parameters created elsewhere
# so wrapping this in a loose try/except.
try:
cls._update_signature()
except Exception:
# The super signature has been changed so we need to get the one
# from the class constructor directly.
cls.__signature__ = inspect.signature(cls.__init__)
@classmethod
def _update_signature(cls):
defaults = cls._modified_slots_defaults()
new_parameters = {}
for i, kls in enumerate(cls.mro()):
if kls.__name__.startswith('_'):
continue
sig = inspect.signature(kls.__init__)
for pname, parameter in sig.parameters.items():
if pname == 'self':
continue
if i >= 1 and parameter.default == inspect.Signature.empty:
continue
if parameter.kind in (inspect.Parameter.VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL):
continue
if getattr(parameter, 'default', None) is Undefined:
if pname not in defaults:
raise LookupError(
f'Argument {pname!r} of Parameter {cls.__name__!r} has no '