[Numpy-discussion] labeling decorators

Fernando Perez fperez.net@gmail....
Wed Jul 30 17:30:51 CDT 2008

Howdy (esp. Alan McIntyre):

I've been using numpy's decorators a lot, many thanks to Matthew B and
Alan for this code!  Here's a snippet to auto-generate labeling
decorators that might come in handy to avoid repetition in creating
decos like @slow & friends.  It's doctested as well as validating
things a bit, feel free to use it if you find it useful.



def make_label_dec(label,ds=None):
    """Factory function to create a decorator that applies one or more labels.

      label : string or sequence
      One or more labels that will be applied by the decorator to the functions
    it decorates.  Labels are attributes of the decorated function with their
    value set to True.

      ds : string
      An optional docstring for the resulting decorator.  If not given, a
      default docstring is auto-generated.

      A decorator.


    A simple labeling decorator:
    >>> slow = make_label_dec('slow')
    >>> print slow.__doc__
    Labels a test as 'slow'

    And one that uses multiple labels and a custom docstring:
    >>> rare = make_label_dec(['slow','hard'],
    ... "Mix labels 'slow' and 'hard' for rare tests.")
    >>> print rare.__doc__
    Mix labels 'slow' and 'hard' for rare tests.

    Now, let's test using this one:
    >>> @rare
    ... def f(): pass
    >>> f.slow
    >>> f.hard

    if isinstance(label,basestring):
        labels = [label]
        labels = label

    # Validate that the given label(s) are OK for use in setattr() by doing a
    # dry run on a dummy function.
    tmp = lambda : None
    for label in labels:

    # This is the actual decorator we'll return
    def decor(f):
        for label in labels:
        return f
    # Apply the user's docstring
    if ds is None:
        ds = "Labels a test as %r" % label
    decor.__doc__ = ds

    return decor

More information about the Numpy-discussion mailing list