Coverage for src/pycse/utils.py: 100.00%

34 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-23 16:23 -0400

1"""Provides utility functions in pycse. 

2 

31. Fuzzy comparisons for float numbers. 

42. An ignore exception decorator 

53. A handy function to read a google sheet. 

6""" 

7 

8# Copyright 2015, John Kitchin 

9# (see accompanying license files for details). 

10import re 

11from urllib.parse import urlparse 

12from contextlib import contextmanager 

13import numpy as np 

14import pandas as pd 

15 

16 

17def feq(x, y, epsilon=np.spacing(1)): 

18 """Fuzzy equals. 

19 

20 x == y with tolerance 

21 """ 

22 return not ((x < (y - epsilon)) or (y < (x - epsilon))) 

23 

24 

25def flt(x, y, epsilon=np.spacing(1)): 

26 """Fuzzy less than. 

27 

28 x < y with tolerance 

29 """ 

30 return x < (y - epsilon) 

31 

32 

33def fgt(x, y, epsilon=np.spacing(1)): 

34 """Fuzzy greater than. 

35 

36 x > y with tolerance 

37 """ 

38 return y < (x - epsilon) 

39 

40 

41def fle(x, y, epsilon=np.spacing(1)): 

42 """Fuzzy less than or equal to. 

43 

44 x <= y with tolerance 

45 """ 

46 return not (y < (x - epsilon)) 

47 

48 

49def fge(x, y, epsilon=np.spacing(1)): 

50 """Fuzzy greater than or equal to . 

51 

52 x >= y with tolerance 

53 """ 

54 return not (x < (y - epsilon)) 

55 

56 

57@contextmanager 

58def ignore_exception(*exceptions): 

59 """Ignore exceptions on decorated function. 

60 

61 >>> with ignore_exception(ZeroDivisionError): 

62 ... print(1/0) 

63 

64 """ 

65 try: 

66 yield 

67 except exceptions as e: 

68 print("caught {}".format(e)) 

69 return 

70 finally: 

71 print("done") 

72 

73 

74def read_gsheet(url, *args, **kwargs): 

75 """Return a dataframe for the Google Sheet at url. 

76 

77 args and kwargs are passed to pd.read_csv 

78 The url should be viewable by anyone with the link. 

79 """ 

80 u = urlparse(url) 

81 if not ((u.netloc == "docs.google.com") and u.path.startswith("/spreadsheets/d/")): 

82 raise Exception(f"{url} does not seem to be for a sheet") 

83 

84 fid = u.path.split("/")[3] 

85 result = re.search("gid=([0-9]*)", u.fragment) 

86 if result: 

87 gid = result.group(1) 

88 else: 

89 # default to main sheet 

90 gid = 0 

91 

92 purl = f"https://docs.google.com/spreadsheets/d/{fid}/export?format=csv&gid={gid}" 

93 

94 return pd.read_csv(purl, *args, **kwargs)