Skip to content

Commit 57092fd

Browse files
authored
Merge pull request #3952 from fonttools/add-ttfont-type-hints
Break off typing part of #3826
2 parents 972dd3a + c51674d commit 57092fd

File tree

7 files changed

+706
-117
lines changed

7 files changed

+706
-117
lines changed

Lib/fontTools/misc/configTools.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,9 @@ def register_option(
224224

225225
def __init__(
226226
self,
227-
values: Union[AbstractConfig, Dict[Union[Option, str], Any]] = {},
227+
values: Union[
228+
AbstractConfig, Dict[Union[Option, str], Any], Mapping[str, Any]
229+
] = {},
228230
parse_values: bool = False,
229231
skip_unknown: bool = False,
230232
):

Lib/fontTools/misc/fixedTools.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
MAX_F2DOT14 = 0x7FFF / (1 << 14)
4040

4141

42-
def fixedToFloat(value, precisionBits):
42+
def fixedToFloat(value: float, precisionBits: int) -> float:
4343
"""Converts a fixed-point number to a float given the number of
4444
precision bits.
4545

Lib/fontTools/misc/xmlWriter.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
"""xmlWriter.py -- Simple XML authoring class"""
22

3+
from __future__ import annotations
4+
5+
from typing import BinaryIO, Callable, TextIO
36
from fontTools.misc.textTools import byteord, strjoin, tobytes, tostr
47
import sys
58
import os
@@ -25,17 +28,22 @@
2528
class XMLWriter(object):
2629
def __init__(
2730
self,
28-
fileOrPath,
29-
indentwhite=INDENT,
30-
idlefunc=None,
31-
encoding="utf_8",
32-
newlinestr="\n",
33-
):
31+
fileOrPath: str | os.PathLike[str] | BinaryIO | TextIO,
32+
indentwhite: str = INDENT,
33+
idlefunc: Callable[[], None] | None = None,
34+
encoding: str = "utf_8",
35+
newlinestr: str | bytes = "\n",
36+
) -> None:
3437
if encoding.lower().replace("-", "").replace("_", "") != "utf8":
3538
raise Exception("Only UTF-8 encoding is supported.")
3639
if fileOrPath == "-":
3740
fileOrPath = sys.stdout
41+
self.filename: str | os.PathLike[str] | None
3842
if not hasattr(fileOrPath, "write"):
43+
if not isinstance(fileOrPath, (str, os.PathLike)):
44+
raise TypeError(
45+
"fileOrPath must be a file path (str or PathLike) if it isn't an object with a `write` method."
46+
)
3947
self.filename = fileOrPath
4048
self.file = open(fileOrPath, "wb")
4149
self._closeStream = True
@@ -74,8 +82,9 @@ def __enter__(self):
7482
def __exit__(self, exception_type, exception_value, traceback):
7583
self.close()
7684

77-
def close(self):
85+
def close(self) -> None:
7886
if self._closeStream:
87+
assert not isinstance(self.file, (str, os.PathLike))
7988
self.file.close()
8089

8190
def write(self, string, indent=True):
@@ -196,7 +205,7 @@ def escape(data):
196205
if len(data) > maxLen:
197206
preview = repr(data[:maxLen])[1:-1] + "..."
198207
TTX_LOG.warning(
199-
"Illegal XML character(s) found; replacing offending " "string %r with %r",
208+
"Illegal XML character(s) found; replacing offending string %r with %r",
200209
preview,
201210
REPLACEMENT,
202211
)

Lib/fontTools/ttLib/sfnt.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313
a table's length changes you need to rewrite the whole file anyway.
1414
"""
1515

16+
from __future__ import annotations
17+
18+
from collections.abc import KeysView
1619
from io import BytesIO
1720
from types import SimpleNamespace
1821
from fontTools.misc.textTools import Tag
@@ -84,7 +87,7 @@ def __init__(self, file, checkChecksums=0, fontNumber=-1):
8487

8588
if self.sfntVersion not in ("\x00\x01\x00\x00", "OTTO", "true"):
8689
raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)")
87-
tables = {}
90+
tables: dict[Tag, DirectoryEntry] = {}
8891
for i in range(self.numTables):
8992
entry = self.DirectoryEntry()
9093
entry.fromFile(self.file)
@@ -96,15 +99,15 @@ def __init__(self, file, checkChecksums=0, fontNumber=-1):
9699
if self.flavor == "woff":
97100
self.flavorData = WOFFFlavorData(self)
98101

99-
def has_key(self, tag):
102+
def has_key(self, tag: str | bytes) -> bool:
100103
return tag in self.tables
101104

102105
__contains__ = has_key
103106

104-
def keys(self):
107+
def keys(self) -> KeysView[Tag]:
105108
return self.tables.keys()
106109

107-
def __getitem__(self, tag):
110+
def __getitem__(self, tag: str | bytes) -> bytes:
108111
"""Fetch the raw table data."""
109112
entry = self.tables[Tag(tag)]
110113
data = entry.loadData(self.file)
@@ -122,10 +125,10 @@ def __getitem__(self, tag):
122125
log.warning("bad checksum for '%s' table", tag)
123126
return data
124127

125-
def __delitem__(self, tag):
128+
def __delitem__(self, tag: str | bytes) -> None:
126129
del self.tables[Tag(tag)]
127130

128-
def close(self):
131+
def close(self) -> None:
129132
self.file.close()
130133

131134
# We define custom __getstate__ and __setstate__ to make SFNTReader pickle-able

Lib/fontTools/ttLib/tables/_a_v_a_r.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
from __future__ import annotations
2+
3+
from typing import Mapping, TYPE_CHECKING
14
from fontTools.misc import sstruct
25
from fontTools.misc.fixedTools import (
36
fixedToFloat as fi2fl,
@@ -20,6 +23,9 @@
2023

2124
from .otBase import BaseTTXConverter
2225

26+
if TYPE_CHECKING:
27+
from ..ttFont import TTFont
28+
2329

2430
class table__a_v_a_r(BaseTTXConverter):
2531
"""Axis Variations table
@@ -143,8 +149,9 @@ def fromXML(self, name, attrs, content, ttFont):
143149
else:
144150
super().fromXML(name, attrs, content, ttFont)
145151

146-
def renormalizeLocation(self, location, font, dropZeroes=True):
147-
152+
def renormalizeLocation(
153+
self, location: Mapping[str, float], font: TTFont, dropZeroes: bool = True
154+
) -> dict[str, float]:
148155
majorVersion = getattr(self, "majorVersion", 1)
149156

150157
if majorVersion not in (1, 2):

0 commit comments

Comments
 (0)