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
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-23 16:23 -0400
1"""Provides utility functions in pycse.
31. Fuzzy comparisons for float numbers.
42. An ignore exception decorator
53. A handy function to read a google sheet.
6"""
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
17def feq(x, y, epsilon=np.spacing(1)):
18 """Fuzzy equals.
20 x == y with tolerance
21 """
22 return not ((x < (y - epsilon)) or (y < (x - epsilon)))
25def flt(x, y, epsilon=np.spacing(1)):
26 """Fuzzy less than.
28 x < y with tolerance
29 """
30 return x < (y - epsilon)
33def fgt(x, y, epsilon=np.spacing(1)):
34 """Fuzzy greater than.
36 x > y with tolerance
37 """
38 return y < (x - epsilon)
41def fle(x, y, epsilon=np.spacing(1)):
42 """Fuzzy less than or equal to.
44 x <= y with tolerance
45 """
46 return not (y < (x - epsilon))
49def fge(x, y, epsilon=np.spacing(1)):
50 """Fuzzy greater than or equal to .
52 x >= y with tolerance
53 """
54 return not (x < (y - epsilon))
57@contextmanager
58def ignore_exception(*exceptions):
59 """Ignore exceptions on decorated function.
61 >>> with ignore_exception(ZeroDivisionError):
62 ... print(1/0)
64 """
65 try:
66 yield
67 except exceptions as e:
68 print("caught {}".format(e))
69 return
70 finally:
71 print("done")
74def read_gsheet(url, *args, **kwargs):
75 """Return a dataframe for the Google Sheet at url.
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")
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
92 purl = f"https://docs.google.com/spreadsheets/d/{fid}/export?format=csv&gid={gid}"
94 return pd.read_csv(purl, *args, **kwargs)