|
23 | 23 | from types import FunctionType
|
24 | 24 |
|
25 | 25 | import tqdm
|
| 26 | +import traitlets |
26 | 27 | import zmq
|
27 | 28 | from dateutil.parser import parse as dateutil_parse
|
28 | 29 | from dateutil.tz import tzlocal
|
@@ -720,3 +721,63 @@ def _locate_profiles(profiles=None):
|
720 | 721 | def shlex_join(cmd):
|
721 | 722 | """Backport shlex.join to Python < 3.8"""
|
722 | 723 | return ' '.join(shlex.quote(s) for s in cmd)
|
| 724 | + |
| 725 | + |
| 726 | +_traitlet_annotations = { |
| 727 | + traitlets.Bool: bool, |
| 728 | + traitlets.Integer: int, |
| 729 | + traitlets.Float: float, |
| 730 | + traitlets.List: list, |
| 731 | + traitlets.Dict: dict, |
| 732 | + traitlets.Set: set, |
| 733 | + traitlets.Unicode: str, |
| 734 | + traitlets.Tuple: tuple, |
| 735 | +} |
| 736 | + |
| 737 | + |
| 738 | +class _TraitAnnotation: |
| 739 | + """Trait annotation for a trait type""" |
| 740 | + |
| 741 | + def __init__(self, trait_type): |
| 742 | + self.trait_type = trait_type |
| 743 | + |
| 744 | + def __repr__(self): |
| 745 | + return self.trait_type.__name__ |
| 746 | + |
| 747 | + |
| 748 | +def _trait_annotation(trait_type): |
| 749 | + """Return an annotation for a trait""" |
| 750 | + if trait_type in _traitlet_annotations: |
| 751 | + return _traitlet_annotations[trait_type] |
| 752 | + else: |
| 753 | + annotation = _traitlet_annotations[trait_type] = _TraitAnnotation(trait_type) |
| 754 | + return annotation |
| 755 | + |
| 756 | + |
| 757 | +def _traitlet_signature(cls): |
| 758 | + """Add traitlet-based signature to a class""" |
| 759 | + parameters = [] |
| 760 | + for name, trait in cls.class_traits().items(): |
| 761 | + if name.startswith("_"): |
| 762 | + # omit private traits |
| 763 | + continue |
| 764 | + if hasattr(trait, 'default'): |
| 765 | + # traitlets 5 |
| 766 | + default = trait.default() |
| 767 | + else: |
| 768 | + default = trait.default_value |
| 769 | + if default is traitlets.Undefined: |
| 770 | + default = None |
| 771 | + |
| 772 | + annotation = _trait_annotation(trait.__class__) |
| 773 | + |
| 774 | + parameters.append( |
| 775 | + inspect.Parameter( |
| 776 | + name=name, |
| 777 | + kind=inspect.Parameter.KEYWORD_ONLY, |
| 778 | + annotation=annotation, |
| 779 | + default=default, |
| 780 | + ) |
| 781 | + ) |
| 782 | + cls.__signature__ = inspect.Signature(parameters) |
| 783 | + return cls |
0 commit comments