Skip to content

Commit ce070e6

Browse files
committed
Added additional type annotations
1 parent aed89bd commit ce070e6

File tree

10 files changed

+104
-79
lines changed

10 files changed

+104
-79
lines changed

domdf_python_tools/bases.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from abc import ABC, abstractmethod
2929
from collections import UserList
3030
from pprint import pformat
31+
from typing import Any, Callable, Dict, Iterable, Tuple
3132

3233
# 3rd party
3334
import pydash # type: ignore
@@ -42,14 +43,14 @@ class Dictable(ABC):
4243
def __init__(self, *args, **kwargs):
4344
pass
4445

45-
def __str__(self):
46+
def __str__(self) -> str:
4647
return self.__repr__()
4748

48-
def __iter__(self):
49+
def __iter__(self) -> Iterable[Tuple[str, Any]]:
4950
for key, value in self.__dict__.items():
5051
yield key, value
5152

52-
def __getstate__(self):
53+
def __getstate__(self) -> Dict[str, Any]:
5354
return self.__dict__
5455

5556
def __setstate__(self, state):
@@ -66,14 +67,14 @@ def __deepcopy__(self, memodict={}):
6667
def __dict__(self):
6768
return dict()
6869

69-
def __eq__(self, other):
70+
def __eq__(self, other) -> bool:
7071
if isinstance(other, self.__class__):
7172
return pydash.predicates.is_match(other.__dict__, self.__dict__)
7273

7374
return NotImplemented
7475

7576

76-
def namedlist(name="NamedList"):
77+
def namedlist(name="NamedList") -> Callable:
7778
"""
7879
A factory function to return a custom list subclass with a name
7980
@@ -88,10 +89,10 @@ class NamedList(UserList):
8889
A list with a name
8990
"""
9091

91-
def __repr__(self):
92+
def __repr__(self) -> str:
9293
return f"{super().__repr__()}"
9394

94-
def __str__(self):
95+
def __str__(self) -> str:
9596
return f"{self.__class__.__name__}{pformat(list(self))}"
9697

9798
NamedList.__name__ = name

domdf_python_tools/dates.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -39,29 +39,34 @@
3939
try:
4040
import pytz
4141

42-
def get_utc_offset(tz, date: datetime.datetime = None) -> Optional[datetime.timedelta]:
42+
def get_utc_offset(
43+
tz: Union[datetime.tzinfo, str],
44+
date: Optional[datetime.datetime] = None,
45+
) -> Optional[datetime.timedelta]:
4346
"""
4447
Returns the offset between UTC and the requested timezone on the given date.
4548
If ``date`` is ``None`` then the current date is used.
4649
4750
:param tz: ``pytz.timezone`` or a string representing the timezone
4851
:type tz:
4952
:param date: The date to obtain the UTC offset for
50-
:type date: python:datetime.datetime, optional
5153
5254
:return:
53-
:rtype: datetime.timedelta or None
5455
"""
5556

5657
if date is None:
5758
date = datetime.datetime.utcnow()
5859

60+
timezone: Optional[datetime.tzinfo]
61+
5962
if isinstance(tz, str):
60-
tz = get_timezone(tz, date)
63+
timezone = get_timezone(tz, date)
64+
else:
65+
timezone = tz
6166

62-
return date.replace(tzinfo=pytz.utc).astimezone(tz).utcoffset()
67+
return date.replace(tzinfo=pytz.utc).astimezone(timezone).utcoffset()
6368

64-
def get_timezone(tz: str, date: datetime.datetime = None) -> Optional[datetime.tzinfo]:
69+
def get_timezone(tz: str, date: Optional[datetime.datetime] = None) -> Optional[datetime.tzinfo]:
6570
"""
6671
Returns a localized :class:`pytz.timezone` object for the given date.
6772
If ``date`` is ``None`` then the current date is used.
@@ -72,7 +77,6 @@ def get_timezone(tz: str, date: datetime.datetime = None) -> Optional[datetime.t
7277
:type date: datetime.datetime, optional
7378
7479
:return:
75-
:rtype: datetime.tzinfo or None
7680
"""
7781

7882
if date is None:
@@ -82,7 +86,7 @@ def get_timezone(tz: str, date: datetime.datetime = None) -> Optional[datetime.t
8286

8387
return pytz.timezone(tz).localize(d).tzinfo
8488

85-
def current_tzinfo():
89+
def current_tzinfo() -> Optional[datetime.tzinfo]:
8690
"""
8791
Returns a tzinfo object for the current timezone
8892
@@ -109,25 +113,23 @@ def current_tzinfo():
109113
# return datetime.astimezone(current_tzinfo).timestamp()
110114
#
111115

112-
def set_timezone(obj, tzinfo):
116+
def set_timezone(obj: datetime.datetime, tzinfo: datetime.tzinfo) -> datetime.datetime:
113117
"""
114118
Sets the timezone / tzinfo of the given :class:`datetime.datetime` object.
115119
This will not convert the time (i.e. the hours will stay the same).
116120
Use :meth:`python:datetime.datetime.astimezone` to accomplish that.
117121
118122
:param obj:
119-
:type obj:
120123
:param tzinfo:
121-
:type tzinfo:
122124
123125
:return:
124-
:rtype:
125126
"""
126127

127128
return obj.replace(tzinfo=tzinfo)
128129

129130
def utc_timestamp_to_datetime(
130-
utc_timestamp: Union[float, int], output_tz: datetime.tzinfo = None
131+
utc_timestamp: Union[float, int],
132+
output_tz: Optional[datetime.tzinfo] = None,
131133
) -> datetime.datetime:
132134
"""
133135
Convert UTC timestamp (seconds from UNIX epoch) to a :class:`datetime.datetime` object
@@ -143,7 +145,7 @@ def utc_timestamp_to_datetime(
143145
:type utc_timestamp: float, int
144146
:param output_tz: The timezone to output the datetime object for.
145147
If None it will be inferred.
146-
:type output_tz: datetime.tzinfo
148+
:type output_tz: datetime.tzinfo, optional
147149
148150
:return: The timestamp as a datetime object.
149151
:rtype: datetime.datetime

domdf_python_tools/doctools.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
# stdlib
3131
import builtins
3232
from textwrap import dedent
33-
from typing import Any, Callable, Type, TypeVar, Union
33+
from typing import Any, Callable, Optional, Sequence, Type, TypeVar, Union
3434

3535
F = TypeVar('F', bound=Callable[..., Any])
3636

@@ -92,7 +92,7 @@ def append_doctring_from_another(target: Union[Type, Callable], original: Union[
9292
target.__doc__ = dedent(original_doc)
9393

9494

95-
def make_sphinx_links(input_string, builtins_list=None):
95+
def make_sphinx_links(input_string: str, builtins_list: Optional[Sequence[str]] = None) -> str:
9696
r"""
9797
Make proper sphinx links out of double-backticked strings in docstring.
9898
@@ -166,7 +166,11 @@ def sphinxify_docstring() -> Callable:
166166
"""
167167

168168
def wrapper(target: F) -> F:
169-
target.__doc__ = make_sphinx_links(target.__doc__)
169+
target_doc = target.__doc__
170+
171+
if target_doc:
172+
target.__doc__ = make_sphinx_links(target_doc)
173+
170174
return target
171175

172176
return wrapper

domdf_python_tools/enums.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ class StrEnum(str, Enum):
4949
An Enum that can be converted into a string
5050
"""
5151

52-
def __str__(self):
52+
def __str__(self) -> str:
5353
return self.value
5454

5555
#

domdf_python_tools/pagesizes/classes.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,9 @@ class BaseSize(namedtuple("__BaseSize", "width, height")):
6161
Base class namedtuple representing a page size, in point
6262
6363
:param width: The page width
64-
:type width: float
64+
:type width: int, float, Decimal or Unit
6565
:param height: The page height
66-
:type height: float
66+
:type height: int, float, Decimal or Unit
6767
"""
6868

6969
__slots__: List[str] = []
@@ -78,7 +78,7 @@ def __new__(cls, width: AnyNumber, height: AnyNumber):
7878
cls._unit(height),
7979
)
8080

81-
def __str__(self):
81+
def __str__(self) -> str:
8282
return f"{self.__class__.__name__}(width={_rounders(self.width, '0')}, height={_rounders(self.height, '0')})"
8383

8484
@classmethod
@@ -162,9 +162,9 @@ class Size_mm(BaseSize):
162162
representing a pagesize in millimeters.
163163
164164
:param width: The page width
165-
:type width: float
165+
:type width: int, float, Decimal or Unit
166166
:param height: The page height
167-
:type height: float
167+
:type height: int, float, Decimal or Unit
168168
"""
169169

170170
_unit = mm
@@ -176,9 +176,9 @@ class Size_inch(BaseSize):
176176
representing a pagesize in inches.
177177
178178
:param width: The page width
179-
:type width: float
179+
:type width: int, float, Decimal or Unit
180180
:param height: The page height
181-
:type height: float
181+
:type height: int, float, Decimal or Unit
182182
"""
183183

184184
_unit = inch
@@ -190,9 +190,9 @@ class Size_cm(BaseSize):
190190
representing a pagesize in centimeters.
191191
192192
:param width: The page width
193-
:type width: float
193+
:type width: int, float, Decimal or Unit
194194
:param height: The page height
195-
:type height: float
195+
:type height: int, float, Decimal or Unit
196196
"""
197197

198198
_unit = cm
@@ -204,9 +204,9 @@ class Size_um(BaseSize):
204204
representing a pagesize in micrometers.
205205
206206
:param width: The page width
207-
:type width: float
207+
:type width: int, float, Decimal or Unit
208208
:param height: The page height
209-
:type height: float
209+
:type height: int, float, Decimal or Unit
210210
"""
211211

212212
_unit = um
@@ -218,9 +218,9 @@ class Size_pica(BaseSize):
218218
representing a pagesize in pica.
219219
220220
:param width: The page width
221-
:type width: float
221+
:type width: int, float, Decimal or Unit
222222
:param height: The page height
223-
:type height: float
223+
:type height: int, float, Decimal or Unit
224224
"""
225225

226226
_unit = pica
@@ -232,9 +232,9 @@ class Size_didot(BaseSize):
232232
representing a pagesize in didots / French Points.
233233
234234
:param width: The page width
235-
:type width: float
235+
:type width: int, float, Decimal or Unit
236236
:param height: The page height
237-
:type height: float
237+
:type height: int, float, Decimal or Unit
238238
"""
239239

240240
_unit = didot
@@ -246,9 +246,9 @@ class Size_cicero(BaseSize):
246246
representing a pagesize in ciceros.
247247
248248
:param width: The page width
249-
:type width: float
249+
:type width: int, float, Decimal or Unit
250250
:param height: The page height
251-
:type height: float
251+
:type height: int, float, Decimal or Unit
252252
"""
253253

254254
_unit = cicero
@@ -260,9 +260,9 @@ class Size_new_didot(BaseSize):
260260
representing a pagesize in new didots.
261261
262262
:param width: The page width
263-
:type width: float
263+
:type width: int, float, Decimal or Unit
264264
:param height: The page height
265-
:type height: float
265+
:type height: int, float, Decimal or Unit
266266
"""
267267

268268
_unit = new_didot
@@ -274,9 +274,9 @@ class Size_new_cicero(BaseSize):
274274
representing a pagesize in ciceros.
275275
276276
:param width: The page width
277-
:type width: float
277+
:type width: int, float, Decimal or Unit
278278
:param height: The page height
279-
:type height: float
279+
:type height: int, float, Decimal or Unit
280280
"""
281281

282282
_unit = new_cicero
@@ -288,9 +288,9 @@ class Size_scaled_point(BaseSize):
288288
representing a pagesize in scaled points.
289289
290290
:param width: The page width
291-
:type width: float
291+
:type width: int, float, Decimal or Unit
292292
:param height: The page height
293-
:type height: float
293+
:type height: int, float, Decimal or Unit
294294
"""
295295

296296
_unit = scaled_point
@@ -302,9 +302,9 @@ class PageSize(BaseSize):
302302
representing a pagesize in point.
303303
304304
:param width: The page width
305-
:type width: float
305+
:type width: int, float, Decimal or Unit
306306
:param height: The page height
307-
:type height: float
307+
:type height: int, float, Decimal or Unit
308308
309309
The pagesize can be converted to other units using the properties below.
310310
"""

domdf_python_tools/pagesizes/utils.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,12 @@ def _sequence_convert_from(seq: Sequence[AnyNumber], from_: AnyNumber) -> Tuple[
7474
return tuple(float(x) * from_ for x in seq)
7575

7676

77+
_measurement_re = re.compile(r"(\d*\.?\d+) *([A-Za-z]*)")
78+
79+
7780
def parse_measurement(measurement):
7881
# TODO: docstring
79-
match = re.findall(r"(\d*\.?\d+) *([A-Za-z]*)", measurement)[0]
82+
match = _measurement_re.findall(measurement)[0]
8083
print(match)
8184
print(len(match))
8285
if len(match) < 2:

domdf_python_tools/paths.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
import os
4949
import pathlib
5050
import shutil
51-
from typing import AnyStr, Callable, Union
51+
from typing import Callable, Optional, Union
5252

5353

5454
def append(var: str, filename: Union[str, pathlib.Path, os.PathLike]):
@@ -74,7 +74,7 @@ def copytree(
7474
src: Union[str, pathlib.Path, os.PathLike],
7575
dst: Union[str, pathlib.Path, os.PathLike],
7676
symlinks: bool = False,
77-
ignore: Callable = None,
77+
ignore: Optional[Callable] = None,
7878
):
7979
"""
8080
Alternative to :func:`shutil.copytree` to work in some situations where it doesn't.
@@ -203,7 +203,7 @@ def read(filename: Union[str, pathlib.Path, os.PathLike]) -> str:
203203

204204
def relpath(
205205
path: Union[str, pathlib.Path, os.PathLike],
206-
relative_to: Union[str, pathlib.Path, os.PathLike] = None
206+
relative_to: Optional[Union[str, pathlib.Path, os.PathLike]] = None
207207
) -> pathlib.Path:
208208
"""
209209
Returns the path for the given file or directory relative to the given

domdf_python_tools/py.typed

Whitespace-only changes.

0 commit comments

Comments
 (0)