infdate 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
infdate/__init__.py ADDED
@@ -0,0 +1,282 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """
4
+ infdate: a wrapper around standard library’s datetime.date objects,
5
+ capable of representing positive and negative infinity
6
+ """
7
+
8
+ import datetime
9
+ import math
10
+
11
+ from typing import final, overload, Any, Final, TypeVar
12
+
13
+ INFINITY: Final = math.inf
14
+ NEGATIVE_INFINITY: Final = -math.inf
15
+
16
+ INFINITE_DATE_DISPLAY: Final = "<inf>"
17
+ NEGATIVE_INFINITE_DATE_DISPLAY: Final = "<-inf>"
18
+
19
+ ISO_DATE_FORMAT: Final = "%Y-%m-%d"
20
+ ISO_DATETIME_FORMAT_UTC: Final = f"{ISO_DATE_FORMAT}T%H:%M:%S.%f%Z"
21
+
22
+ D = TypeVar("D", bound="Date")
23
+
24
+
25
+ class DateMeta(type):
26
+ """Date metaclass"""
27
+
28
+ @property
29
+ def min(cls: type[D], /) -> D: # type: ignore[misc]
30
+ """Minimum possible Date"""
31
+ return cls(NEGATIVE_INFINITY)
32
+
33
+ @property
34
+ def max(cls: type[D], /) -> D: # type: ignore[misc]
35
+ """Maximum possible Date"""
36
+ return cls(INFINITY)
37
+
38
+
39
+ class Date(metaclass=DateMeta):
40
+ """Date object capable of representing negative or positive infinity"""
41
+
42
+ resolution = 1
43
+
44
+ @overload
45
+ def __init__(self: D, year_or_strange_number: float, /) -> None: ...
46
+ @overload
47
+ def __init__(
48
+ self: D, year_or_strange_number: int, month: int, day: int, /
49
+ ) -> None: ...
50
+ @final
51
+ def __init__(
52
+ self: D, year_or_strange_number: int | float, /, month: int = 0, day: int = 0
53
+ ) -> None:
54
+ """Create a date-like object"""
55
+ if isinstance(year_or_strange_number, int):
56
+ self.__wrapped_date_obj: datetime.date | None = datetime.date(
57
+ int(year_or_strange_number), month, day
58
+ )
59
+ self.__ordinal: float | int = self.__wrapped_date_obj.toordinal()
60
+ elif math.isnan(year_or_strange_number):
61
+ raise ValueError("Cannot instantiate from NaN")
62
+ elif year_or_strange_number in (
63
+ INFINITY,
64
+ NEGATIVE_INFINITY,
65
+ ):
66
+ self.__ordinal = year_or_strange_number
67
+ self.__wrapped_date_obj = None
68
+ else:
69
+ raise ValueError("Cannot instantiate from a regular deterministic float")
70
+ #
71
+
72
+ def toordinal(self: D) -> float | int:
73
+ """to ordinal (almost like datetime.date.toordinal())"""
74
+ return self.__ordinal
75
+
76
+ def get_date_object(self: D) -> datetime.date:
77
+ """Return the wrapped date object"""
78
+ if isinstance(self.__wrapped_date_obj, datetime.date):
79
+ return self.__wrapped_date_obj
80
+ #
81
+ raise ValueError("Non-deterministic date")
82
+
83
+ @property
84
+ def year(self: D) -> int:
85
+ """shortcut: year"""
86
+ return self.get_date_object().year
87
+
88
+ @property
89
+ def month(self: D) -> int:
90
+ """shortcut: month"""
91
+ return self.get_date_object().month
92
+
93
+ @property
94
+ def day(self: D) -> int:
95
+ """shortcut: day"""
96
+ return self.get_date_object().day
97
+
98
+ def replace(self: D, /, year: int = 0, month: int = 0, day: int = 0) -> D:
99
+ """Return a copy with year, month, and/or date replaced"""
100
+ internal_object = self.get_date_object()
101
+ return self.factory(
102
+ internal_object.replace(
103
+ year=year or internal_object.year,
104
+ month=month or internal_object.month,
105
+ day=day or internal_object.day,
106
+ )
107
+ )
108
+
109
+ def isoformat(self: D) -> str:
110
+ """Date representation in ISO format"""
111
+ return self.strftime(ISO_DATE_FORMAT)
112
+
113
+ def strftime(self: D, fmt: str, /) -> str:
114
+ """String representation of the date"""
115
+ try:
116
+ date_object = self.get_date_object()
117
+ except ValueError as error:
118
+ if self.__ordinal == INFINITY:
119
+ return INFINITE_DATE_DISPLAY
120
+ #
121
+ if self.__ordinal == NEGATIVE_INFINITY:
122
+ return NEGATIVE_INFINITE_DATE_DISPLAY
123
+ #
124
+ raise error from error
125
+ #
126
+ return date_object.strftime(fmt or ISO_DATE_FORMAT)
127
+
128
+ __format__ = strftime
129
+
130
+ def __bool__(self: D) -> bool:
131
+ """True if a real date is wrapped"""
132
+ return self.__wrapped_date_obj is not None
133
+
134
+ def __hash__(self: D) -> int:
135
+ """hash value"""
136
+ return hash(f"date with ordinal {self.__ordinal}")
137
+
138
+ def __add__(self: D, delta: int | float, /) -> D:
139
+ """Add other, respecting maybe-nondeterministic values"""
140
+ for observed_item in (delta, self.__ordinal):
141
+ for infinity_form in (INFINITY, NEGATIVE_INFINITY):
142
+ if observed_item == infinity_form:
143
+ return self.factory(infinity_form)
144
+ #
145
+ #
146
+ #
147
+ return self.fromordinal(int(self.__ordinal) + int(delta))
148
+
149
+ @overload
150
+ def __sub__(self: D, other: int | float, /) -> D: ...
151
+ @overload
152
+ def __sub__(self: D, other: D, /) -> int | float: ...
153
+ @final
154
+ def __sub__(self: D, other: D | int | float, /) -> D | int | float:
155
+ """subtract other, respecting possibly nondeterministic values"""
156
+ if isinstance(other, (int, float)):
157
+ return self + -other
158
+ #
159
+ return self.__ordinal - other.toordinal()
160
+
161
+ def __lt__(self: D, other: D, /) -> bool:
162
+ """Rich comparison: less"""
163
+ return self.__ordinal < other.toordinal()
164
+
165
+ def __le__(self: D, other: D, /) -> bool:
166
+ """Rich comparison: less or equal"""
167
+ return self < other or self == other
168
+
169
+ def __gt__(self: D, other: D, /) -> bool:
170
+ """Rich comparison: greater"""
171
+ return self.__ordinal > other.toordinal()
172
+
173
+ def __ge__(self: D, other: D, /) -> bool:
174
+ """Rich comparison: greater or equal"""
175
+ return self > other or self == other
176
+
177
+ def __eq__(self: D, other, /) -> bool:
178
+ """Rich comparison: equals"""
179
+ return self.__ordinal == other.toordinal()
180
+
181
+ def __ne__(self: D, other, /) -> bool:
182
+ """Rich comparison: does not equal"""
183
+ return self.__ordinal != other.toordinal()
184
+
185
+ def __repr__(self: D, /) -> str:
186
+ """String representation of the object"""
187
+ try:
188
+ return f"{self.__class__.__name__}({self.year}, {self.month}, {self.day})"
189
+ except ValueError:
190
+ return f"{self.__class__.__name__}({repr(self.__ordinal)})"
191
+ #
192
+
193
+ def __str__(self: D, /) -> str:
194
+ """String representation of the date"""
195
+ return self.isoformat()
196
+
197
+ @classmethod
198
+ def today(cls: type[D], /) -> D:
199
+ """Today as Date object"""
200
+ return cls.factory(datetime.date.today())
201
+
202
+ @classmethod
203
+ def fromisoformat(
204
+ cls: type[D],
205
+ source: str,
206
+ /,
207
+ ) -> D:
208
+ """Create an instance from an iso format representation"""
209
+ lower_source_stripped = source.strip().lower()
210
+ if lower_source_stripped == INFINITE_DATE_DISPLAY:
211
+ return cls(INFINITY)
212
+ #
213
+ if lower_source_stripped == NEGATIVE_INFINITE_DATE_DISPLAY:
214
+ return cls(NEGATIVE_INFINITY)
215
+ #
216
+ return cls.factory(datetime.date.fromisoformat(lower_source_stripped))
217
+
218
+ @classmethod
219
+ def fromisocalendar(
220
+ cls: type[D],
221
+ /,
222
+ year: int,
223
+ week: int,
224
+ day: int,
225
+ ) -> D:
226
+ """Create an instance from an iso calendar date"""
227
+ return cls.factory(datetime.date.fromisocalendar(year, week, day))
228
+
229
+ @classmethod
230
+ def fromordinal(
231
+ cls: type[D],
232
+ source: float | int,
233
+ /,
234
+ ) -> D:
235
+ """Create an instance from a date ordinal"""
236
+ if isinstance(source, int):
237
+ return cls.factory(datetime.date.fromordinal(source))
238
+ #
239
+ if source in (NEGATIVE_INFINITY, INFINITY):
240
+ return cls(source)
241
+ #
242
+ raise ValueError(f"Invalid source for .fromordinal(): {source!r}")
243
+
244
+ @classmethod
245
+ def from_api_data(
246
+ cls: type[D],
247
+ source: Any,
248
+ /,
249
+ *,
250
+ fmt: str = ISO_DATETIME_FORMAT_UTC,
251
+ past_bound: bool = False,
252
+ ) -> D:
253
+ """Create an instance from string or another type,
254
+ assuming infinity in the latter case
255
+ """
256
+ if isinstance(source, str):
257
+ return cls.factory(datetime.datetime.strptime(source, fmt))
258
+ #
259
+ return cls(NEGATIVE_INFINITY if past_bound else INFINITY)
260
+
261
+ @overload
262
+ @classmethod
263
+ def factory(cls: type[D], source: datetime.date | datetime.datetime, /) -> D: ...
264
+ @overload
265
+ @classmethod
266
+ def factory(cls: type[D], source: float, /) -> D: ...
267
+ @final
268
+ @classmethod
269
+ def factory(
270
+ cls: type[D], source: datetime.date | datetime.datetime | float, /
271
+ ) -> D:
272
+ """Create a new instance from a datetime.date or datetime.datetime object,
273
+ from
274
+ """
275
+ if isinstance(source, (datetime.date, datetime.datetime)):
276
+ return cls(source.year, source.month, source.day)
277
+ #
278
+ return cls(source)
279
+
280
+
281
+ BEFORE_BIG_BANG: Final = Date.max
282
+ SAINT_GLINGLIN: Final = Date.min
infdate/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """
2
+ Script functionality
3
+ """
4
+
5
+
6
+ def hello() -> str:
7
+ """hello pylint C0116"""
8
+ return "Hello from infdate!"
infdate/py.typed ADDED
File without changes
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: infdate
3
+ Version: 0.1.0
4
+ Summary: Date object wrapper supporting infinity
5
+ Project-URL: Homepage, https://gitlab.com/blackstream-x/infdate
6
+ Project-URL: CI, https://gitlab.com/blackstream-x/infdate/-/pipelines
7
+ Project-URL: Bug Tracker, https://gitlab.com/blackstream-x/infdate/-/issues
8
+ Project-URL: Repository, https://gitlab.com/blackstream-x/infdate.git
9
+ Author-email: Rainer Schwarzbach <rainer@blackstream.de>
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.11
23
+ Description-Content-Type: text/markdown
24
+
25
+ # infdate
26
+
27
+ _Python module for date calculations implementing a concept of infinity_
28
+
29
+ The **Date** class provided in this package wraps the standard library’s
30
+ **datetime.date** class and adds the capability to specify dates in positive
31
+ (after everything else) or negative (before everything else) infinity,
32
+ and to do calculations (add days, or subtract days or other **Date** instances)
33
+ with these objects.
34
+
35
+ For easier usage, differences are expressed as integers (1 = one day)
36
+ or floats (inf and -inf _only_).
37
+
38
+ These capabilities can come handy when dealing with API representations of dates,
39
+ eg. in GitLab’s [Personal Access Tokens API].
40
+
41
+ * * *
42
+ [Personal Access Tokens API]: https://docs.gitlab.com/api/personal_access_tokens/
@@ -0,0 +1,7 @@
1
+ infdate/__init__.py,sha256=_gJvzSUHx1bvs6xCWI9fhDniWhFR2RD5VQUaFKZoP7U,8890
2
+ infdate/__main__.py,sha256=RtLjAiDLfFTpSFuU68nKhVfBUkxqDhhIY2jNxgL2cW4,113
3
+ infdate/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ infdate-0.1.0.dist-info/METADATA,sha256=p-zgj6Xlvz79e_QBIC0DrmHBilf83e-u7olcyyjLDA4,1821
5
+ infdate-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
6
+ infdate-0.1.0.dist-info/licenses/LICENSE,sha256=867pxriiObx28vCU1JsRtu3H9kUKyl54e0-xl1IIv3Y,913
7
+ infdate-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,18 @@
1
+ MIT No Attribution
2
+
3
+ Copyright 2025 Rainer Schwarzbach
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18
+ SOFTWARE.