-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
94 lines (71 loc) · 2.55 KB
/
Copy pathmodels.py
File metadata and controls
94 lines (71 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import re
from typing import Any
# our beautiful and useless data structure for storing a location:
class Location:
latitude: float
longitude: float
def __init__(self, lat: float, long: float) -> None:
self.latitude = lat
self.longitude = long
def __str__(self) -> str:
try:
return self._location().address
except Exception:
return f"({self.latitude}, {self.longitude})"
def _location(self):
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="konfi-converters-example/1.0 (https://github.com/gieseladev/konfi)")
return geolocator.reverse((self.latitude, self.longitude), addressdetails=False)
# let's also define a nice temperature data structure
class Temperature:
_kelvin: float
def __init__(self, kelvin: float = 0) -> None:
self.kelvin = kelvin
def __str__(self) -> str:
return f"{self.degrees:.1f} °C"
@property
def kelvin(self) -> float:
return self._kelvin
@kelvin.setter
def kelvin(self, value: float) -> None:
if value < 0:
raise ValueError("Temperature cannot be less than 0 Kelvin")
self._kelvin = value
@property
def degrees(self) -> float:
return self.kelvin - 273.15
@degrees.setter
def degrees(self, value: float) -> None:
self.kelvin = value + 273.15
@property
def stupid(self) -> float:
return self.degrees * 1.8 + 32
@stupid.setter
def stupid(self, value: float) -> None:
self.degrees = (value - 32) / 1.8
@classmethod
def create(cls, value: Any):
inst = cls()
if isinstance(value, str):
# mad regex
match = re.match(r"(\d+[.\d]*)\s?(°?c|°?f|k)", value, re.IGNORECASE)
if match is None:
raise ValueError(f"Invalid temperature: {value!r}")
temp_str, symbol = match.groups()
temp = float(temp_str)
symbol = symbol.lstrip("°").lower()
# poor man's switch
if symbol == "k":
inst.kelvin = temp
elif symbol == "c":
inst.degrees = temp
elif symbol == "f":
inst.stupid = temp
else:
raise ValueError(f"unknown unit: {symbol!r}")
elif isinstance(value, (float, int)):
# yes, unitless numbers are de facto celsius, fight me
inst.degrees = value
else:
raise TypeError("Invalid value type for temperature")
return inst