Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2Boilerplate functions used in defining binary operations. 

3""" 

4from functools import wraps 

5 

6from pandas._libs.lib import item_from_zerodim 

7 

8from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries 

9 

10 

11def unpack_zerodim_and_defer(name: str): 

12 """ 

13 Boilerplate for pandas conventions in arithmetic and comparison methods. 

14 

15 Parameters 

16 ---------- 

17 name : str 

18 

19 Returns 

20 ------- 

21 decorator 

22 """ 

23 

24 def wrapper(method): 

25 return _unpack_zerodim_and_defer(method, name) 

26 

27 return wrapper 

28 

29 

30def _unpack_zerodim_and_defer(method, name: str): 

31 """ 

32 Boilerplate for pandas conventions in arithmetic and comparison methods. 

33 

34 Ensure method returns NotImplemented when operating against "senior" 

35 classes. Ensure zero-dimensional ndarrays are always unpacked. 

36 

37 Parameters 

38 ---------- 

39 method : binary method 

40 name : str 

41 

42 Returns 

43 ------- 

44 method 

45 """ 

46 

47 is_cmp = name.strip("__") in {"eq", "ne", "lt", "le", "gt", "ge"} 

48 

49 @wraps(method) 

50 def new_method(self, other): 

51 

52 if is_cmp and isinstance(self, ABCIndexClass) and isinstance(other, ABCSeries): 

53 # For comparison ops, Index does *not* defer to Series 

54 pass 

55 else: 

56 for cls in [ABCDataFrame, ABCSeries, ABCIndexClass]: 

57 if isinstance(self, cls): 

58 break 

59 if isinstance(other, cls): 

60 return NotImplemented 

61 

62 other = item_from_zerodim(other) 

63 

64 return method(self, other) 

65 

66 return new_method