Skip to content

Commit 0985a5a

Browse files
committed
Add type annotations and isort configuration
1 parent e097010 commit 0985a5a

File tree

19 files changed

+119
-100
lines changed

19 files changed

+119
-100
lines changed

.isort.cfg

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
[settings]
2+
line_length=115
3+
force_to_top=True
4+
indent=Tab
5+
multi_line_output=3
6+
import_heading_stdlib=stdlib
7+
import_heading_thirdparty=3rd party
8+
import_heading_firstparty=this package
9+
balanced_wrapping=False
10+
lines_between_types=0
11+
use_parentheses=True
12+
default_section=FIRSTPARTY
13+
no_lines_before=LOCALFOLDER

doc-source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
"notfound.extension",
4444
"sphinx_tabs.tabs",
4545
"sphinx-prompt",
46-
'sphinx_autodoc_typehints',
46+
"sphinx_autodoc_typehints",
4747
]
4848

4949
sphinxemoji_style = 'twemoji'

doc-source/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ sphinx-autodoc-typehints >=1.10.3
55
sphinx-notfound-page
66
sphinx-prompt >=1.2.0
77
sphinx-tabs >=1.1.13
8+
sphinx_autodoc_typehints >=1.10.3
89
sphinx_rtd_theme
910
sphinxcontrib-httpdomain >=1.7.0
1011
sphinxemoji >=0.1.6

domdf_python_tools/bases.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from pprint import pformat
3131

3232
# 3rd party
33-
import pydash
33+
import pydash # type: ignore
3434

3535

3636
class Dictable(ABC):

domdf_python_tools/dates.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,23 +34,24 @@
3434
# stdlib
3535
import datetime
3636
from collections import OrderedDict
37-
from typing import Union
37+
from typing import Optional, Union
3838

3939
# 3rd party
4040
try:
4141
import pytz
4242

43-
def get_utc_offset(tz, date: datetime.datetime = None) -> datetime.timedelta:
43+
def get_utc_offset(tz, date: datetime.datetime = None) -> Optional[datetime.timedelta]:
4444
"""
4545
Returns the offset between UTC and the requested timezone on the given date.
4646
If ``date`` is ``None`` then the current date is used.
4747
4848
:param tz: ``pytz.timezone`` or a string representing the timezone
4949
:type tz:
50-
:param date:
50+
:param date: The date to obtain the UTC offset for
5151
:type date: python:datetime.datetime, optional
52+
5253
:return:
53-
:rtype: datetime.timedelta
54+
:rtype: datetime.timedelta or None
5455
"""
5556

5657
if date is None:
@@ -61,17 +62,18 @@ def get_utc_offset(tz, date: datetime.datetime = None) -> datetime.timedelta:
6162

6263
return date.replace(tzinfo=pytz.utc).astimezone(tz).utcoffset()
6364

64-
def get_timezone(tz: str, date: datetime.datetime = None) -> datetime.timedelta:
65+
def get_timezone(tz: str, date: datetime.datetime = None) -> Optional[datetime.tzinfo]:
6566
"""
6667
Returns a localized :class:`pytz.timezone` object for the given date.
6768
If ``date`` is ``None`` then the current date is used.
6869
6970
:param tz: A string representing a pytz timezone
7071
:type tz: str
71-
:param date:
72-
:type date: python:datetime.datetime, optional
72+
:param date: The date to obtain the timezone for
73+
:type date: datetime.datetime, optional
74+
7375
:return:
74-
:rtype: datetime.timedelta
76+
:rtype: datetime.tzinfo or None
7577
"""
7678

7779
if date is None:
@@ -187,7 +189,7 @@ def parse_month(month: Union[str, int]) -> str:
187189
month = int(month)
188190
except ValueError:
189191
try:
190-
return months[month.capitalize()[:3]]
192+
return months[month.capitalize()[:3]] # type: ignore
191193
except KeyError:
192194
raise ValueError("Unrecognised month value")
193195

domdf_python_tools/doctools.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,10 @@
2929

3030
# stdlib
3131
import builtins
32-
from typing import Callable, Type, Union
32+
from textwrap import dedent
33+
from typing import Any, Callable, Type, TypeVar, Union
34+
35+
F = TypeVar('F', bound=Callable[..., Any])
3336

3437

3538
def deindent_string(string: str) -> str:
@@ -76,10 +79,17 @@ def append_doctring_from_another(target: Union[Type, Callable], original: Union[
7679
:param original: The object to copy the docstring from
7780
"""
7881

79-
deindented_target_doc = deindent_string(target.__doc__)
80-
deindented_original_doc = deindent_string(original.__doc__)
82+
target_doc = target.__doc__
83+
original_doc = original.__doc__
84+
85+
if isinstance(original_doc, str) and isinstance(target_doc, str):
86+
deindented_target_doc = dedent(target_doc)
87+
deindented_original_doc = dedent(original_doc)
88+
89+
target.__doc__ = deindented_target_doc + "\n" + deindented_original_doc
8190

82-
target.__doc__ = deindented_target_doc + "\n" + deindented_original_doc
91+
elif not isinstance(target_doc, str) and isinstance(original_doc, str):
92+
target.__doc__ = dedent(original_doc)
8393

8494

8595
def make_sphinx_links(input_string, builtins_list=None):
@@ -113,21 +123,21 @@ def make_sphinx_links(input_string, builtins_list=None):
113123

114124

115125
# Decorators that call the above functions
116-
def is_documented_by(original: Union[Type, Callable]):
126+
def is_documented_by(original: F) -> Callable:
117127
"""
118128
Decorator to set the docstring of the ``target`` function to that of the ``original`` function.
119129
120130
This may be useful for subclasses or wrappers that use the same arguments.
121131
"""
122132

123-
def wrapper(target: Union[Type, Callable]):
133+
def wrapper(target: F) -> F:
124134
document_object_from_another(target, original)
125135
return target
126136

127137
return wrapper
128138

129139

130-
def append_docstring_from(original: Union[Type, Callable]):
140+
def append_docstring_from(original: F) -> Callable:
131141
"""
132142
Decorator to appends the docstring from the ``original`` function to the ``target`` function.
133143
@@ -138,14 +148,14 @@ def append_docstring_from(original: Union[Type, Callable]):
138148
Bear this in mind if additional indentation is used in the docstring.
139149
"""
140150

141-
def wrapper(target: Union[Type, Callable]):
151+
def wrapper(target: F) -> F:
142152
append_doctring_from_another(target, original)
143153
return target
144154

145155
return wrapper
146156

147157

148-
def sphinxify_docstring():
158+
def sphinxify_docstring() -> Callable:
149159
r"""
150160
Decorator to make proper sphinx links out of double-backticked strings in the docstring.
151161
@@ -155,7 +165,7 @@ def sphinxify_docstring():
155165
`intersphinx_mapping` dict of your conf.py for sphinx.
156166
"""
157167

158-
def wrapper(target: Union[Type, Callable]):
168+
def wrapper(target: F) -> F:
159169
target.__doc__ = make_sphinx_links(target.__doc__)
160170
return target
161171

domdf_python_tools/enums.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
# MA 02110-1301, USA.
2525
#
2626

27-
from aenum import Enum, IntEnum
27+
from aenum import Enum, IntEnum # type: ignore
2828

2929
__all__ = ["IntEnum", "StrEnum"]
3030

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# stdlib
2+
from decimal import Decimal
3+
from typing import Union
4+
5+
AnyNumber = Union[float, int, Decimal]

domdf_python_tools/pagesizes/classes.py

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@
3333

3434
from collections import namedtuple
3535
from collections.abc import Sequence
36+
from typing import List, Tuple
3637

38+
from ._types import AnyNumber
3739
from .units import (
3840
cicero,
3941
cm,
@@ -66,20 +68,17 @@
6668

6769

6870
class BaseSize(namedtuple("__BaseSize", "width, height")):
69-
__slots__ = []
71+
__slots__: List[str] = []
72+
_unit: float = pt
7073

71-
def __new__(cls, width, height):
72-
return super().__new__(
73-
cls,
74-
_rounders(width, "0.000000"),
75-
_rounders(height, "0.000000"),
76-
)
74+
def __new__(cls, width: AnyNumber, height: AnyNumber):
75+
return super().__new__(cls, float(width), float(height))
7776

7877
def __str__(self):
7978
return f"{self.__class__.__name__}(width={_rounders(self.width, '0')}, height={_rounders(self.height, '0')})"
8079

8180
@classmethod
82-
def from_size(cls, size):
81+
def from_size(cls, size: Tuple[AnyNumber, AnyNumber]):
8382
"""
8483
8584
:param size:
@@ -91,7 +90,7 @@ def from_size(cls, size):
9190

9291
return cls(*size)
9392

94-
def landscape(self):
93+
def landscape(self) -> "BaseSize":
9594
"""
9695
Returns the pagesize in landscape orientation
9796
@@ -104,7 +103,7 @@ def landscape(self):
104103
else:
105104
return self
106105

107-
def is_landscape(self):
106+
def is_landscape(self) -> bool:
108107
"""
109108
Returns whether the pagesize is in the landscape orientation
110109
@@ -114,7 +113,7 @@ def is_landscape(self):
114113

115114
return self.width >= self.height
116115

117-
def portrait(self):
116+
def portrait(self) -> "BaseSize":
118117
"""
119118
Returns the pagesize in portrait orientation
120119
@@ -127,7 +126,7 @@ def portrait(self):
127126
else:
128127
return self
129128

130-
def is_portrait(self):
129+
def is_portrait(self) -> bool:
131130
"""
132131
Returns whether the pagesize is in the portrait orientation
133132
@@ -137,7 +136,7 @@ def is_portrait(self):
137136

138137
return self.width < self.height
139138

140-
def is_square(self):
139+
def is_square(self) -> bool:
141140
"""
142141
Returns whether the given pagesize is square
143142
@@ -147,10 +146,8 @@ def is_square(self):
147146

148147
return self.width == self.height
149148

150-
_unit = pt
151-
152149
@classmethod
153-
def from_pt(cls, size):
150+
def from_pt(cls, size: "PageSize"):
154151
"""
155152
156153
:param size:
@@ -164,7 +161,7 @@ def from_pt(cls, size):
164161

165162
return cls(size.width / cls._unit, size.height / cls._unit)
166163

167-
def to_pt(self):
164+
def to_pt(self) -> "PageSize":
168165
"""
169166
170167
:return:
@@ -218,7 +215,7 @@ class Size_scaled_point(BaseSize):
218215

219216

220217
class PageSize(BaseSize):
221-
__slots__ = []
218+
__slots__: List[str] = []
222219

223220
def __new__(cls, width, height, unit=pt):
224221
width, height = convert_from((width, height), unit)

domdf_python_tools/pagesizes/units.py

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,6 @@
3131
# MA 02110-1301, USA.
3232
#
3333

34-
from decimal import Decimal
35-
3634
__all__ = [
3735
"pt",
3836
"inch",
@@ -54,26 +52,15 @@
5452
]
5553

5654

57-
class Unit(Decimal):
58-
59-
def __mul__(self, other):
60-
if isinstance(other, float):
61-
other = Decimal(str(other))
62-
63-
return self.__class__(super().__mul__(other))
64-
65-
__rmul__ = __mul__
66-
67-
6855
# Units
6956
pt = 1
70-
inch = Unit("72.0")
71-
cm = inch / Unit("2.54")
72-
mm = cm * Unit("0.1")
73-
um = mm * Unit("0.01")
74-
pc = pica = Unit("12.0")
75-
dd = didot = Unit("1.07")
57+
inch = 72.0
58+
cm = inch / 2.54
59+
mm = cm * 0.1
60+
um = mm * 0.01
61+
pc = pica = 12.0
62+
dd = didot = 1.07
7663
cc = cicero = dd * 12
77-
nd = new_didot = Unit("1.067")
64+
nd = new_didot = 1.067
7865
nc = new_cicero = nd * 12
7966
sp = scaled_point = 1 / 65536

0 commit comments

Comments
 (0)