github.com/google/grumpy@v0.0.0-20171122020858-3ec87959189c/third_party/stdlib/functools.py (about)

     1  """functools.py - Tools for working with functions and callable objects
     2  """
     3  # Python module wrapper for _functools C module
     4  # to allow utilities written in Python to be added
     5  # to the functools module.
     6  # Written by Nick Coghlan <ncoghlan at gmail.com>
     7  #   Copyright (C) 2006 Python Software Foundation.
     8  # See C source code for _functools credits/copyright
     9  
    10  # from _functools import partial, reduce
    11  import _functools
    12  partial = _functools.partial
    13  reduce = _functools.reduce
    14  
    15  def setattr(d, k, v):
    16    d.__dict__[k] = v
    17  
    18  # update_wrapper() and wraps() are tools to help write
    19  # wrapper functions that can handle naive introspection
    20  
    21  WRAPPER_ASSIGNMENTS = ('__module__', '__name__') #, '__doc__'
    22  WRAPPER_UPDATES = ('__dict__',)
    23  def update_wrapper(wrapper,
    24                     wrapped,
    25                     assigned = WRAPPER_ASSIGNMENTS,
    26                     updated = WRAPPER_UPDATES):
    27      """Update a wrapper function to look like the wrapped function
    28  
    29         wrapper is the function to be updated
    30         wrapped is the original function
    31         assigned is a tuple naming the attributes assigned directly
    32         from the wrapped function to the wrapper function (defaults to
    33         functools.WRAPPER_ASSIGNMENTS)
    34         updated is a tuple naming the attributes of the wrapper that
    35         are updated with the corresponding attribute from the wrapped
    36         function (defaults to functools.WRAPPER_UPDATES)
    37      """
    38      for attr in assigned:
    39          setattr(wrapper, attr, getattr(wrapped, attr))
    40      for attr in updated:
    41          getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
    42      # Return the wrapper so this can be used as a decorator via partial()
    43      return wrapper
    44  
    45  def wraps(wrapped,
    46            assigned = WRAPPER_ASSIGNMENTS,
    47            updated = WRAPPER_UPDATES):
    48      """Decorator factory to apply update_wrapper() to a wrapper function
    49  
    50         Returns a decorator that invokes update_wrapper() with the decorated
    51         function as the wrapper argument and the arguments to wraps() as the
    52         remaining arguments. Default arguments are as for update_wrapper().
    53         This is a convenience function to simplify applying partial() to
    54         update_wrapper().
    55      """
    56      return partial(update_wrapper, wrapped=wrapped,
    57                     assigned=assigned, updated=updated)
    58  
    59  def total_ordering(cls):
    60      """Class decorator that fills in missing ordering methods"""
    61      convert = {
    62          '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)),
    63                     ('__le__', lambda self, other: self < other or self == other),
    64                     ('__ge__', lambda self, other: not self < other)],
    65          '__le__': [('__ge__', lambda self, other: not self <= other or self == other),
    66                     ('__lt__', lambda self, other: self <= other and not self == other),
    67                     ('__gt__', lambda self, other: not self <= other)],
    68          '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)),
    69                     ('__ge__', lambda self, other: self > other or self == other),
    70                     ('__le__', lambda self, other: not self > other)],
    71          '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other),
    72                     ('__gt__', lambda self, other: self >= other and not self == other),
    73                     ('__lt__', lambda self, other: not self >= other)]
    74      }
    75      roots = set(dir(cls)) & set(convert)
    76      if not roots:
    77          raise ValueError('must define at least one ordering operation: < > <= >=')
    78      root = max(roots)       # prefer __lt__ to __le__ to __gt__ to __ge__
    79      for opname, opfunc in convert[root]:
    80          if opname not in roots:
    81              opfunc.__name__ = opname
    82              opfunc.__doc__ = getattr(int, opname).__doc__
    83              setattr(cls, opname, opfunc)
    84      return cls
    85  
    86  def cmp_to_key(mycmp):
    87      """Convert a cmp= function into a key= function"""
    88      class K(object):
    89          __slots__ = ['obj']
    90          def __init__(self, obj, *args):
    91              self.obj = obj
    92          def __lt__(self, other):
    93              return mycmp(self.obj, other.obj) < 0
    94          def __gt__(self, other):
    95              return mycmp(self.obj, other.obj) > 0
    96          def __eq__(self, other):
    97              return mycmp(self.obj, other.obj) == 0
    98          def __le__(self, other):
    99              return mycmp(self.obj, other.obj) <= 0
   100          def __ge__(self, other):
   101              return mycmp(self.obj, other.obj) >= 0
   102          def __ne__(self, other):
   103              return mycmp(self.obj, other.obj) != 0
   104          def __hash__(self):
   105              raise TypeError('hash not implemented')
   106      return K