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
|
import logging
from traitlets import TraitType, TraitError
class Handlers(TraitType):
"""A trait that takes a list of logging handlers and converts
it to a callable that returns that list (thus, making this
trait pickleable).
"""
info_text = "a list of logging handlers"
def validate_elements(self, obj, value):
if len(value) > 0:
# Check that all elements are logging handlers.
for el in value:
if isinstance(el, logging.Handler) is False:
self.element_error(obj)
def element_error(self, obj):
raise TraitError(
"Elements in the '{}' trait of an {} instance "
"must be Python `logging` handler instances."
.format(self.name, obj.__class__.__name__)
)
def validate(self, obj, value):
# If given a callable, call it and set the
# value of this trait to the returned list.
# Verify that the callable returns a list
# of logging handler instances.
if callable(value):
out = value()
self.validate_elements(obj, out)
return out
# If a list, check it's elements to verify
# that each element is a logging handler instance.
elif type(value) == list:
self.validate_elements(obj, value)
return value
else:
self.error(obj, value)
|