Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 021ffb3

Browse files
committed
mathtext: Fix type inconsistency with fontmaps
Previously, some fontmaps used integer keys for some special font entries, but there's no reason why they can't also be strings, which should reduce the type inconsistency across the whole file. Also, fix a couple of other type errors with strict mypy. Fixes matplotlib#31433
1 parent 0adda9f commit 021ffb3

1 file changed

Lines changed: 34 additions & 41 deletions

File tree

lib/matplotlib/_mathtext.py

Lines changed: 34 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -337,20 +337,15 @@ def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlag
337337
# Per-instance cache.
338338
self._get_info = functools.cache(self._get_info) # type: ignore[method-assign]
339339
self._fonts = {}
340-
self.fontmap: dict[str | int, str] = {}
340+
self.fontmap: dict[str, str] = {}
341341

342342
filename = findfont(self.default_font_prop)
343343
default_font = get_font(filename)
344344
self._fonts['default'] = default_font
345345
self._fonts['regular'] = default_font
346346

347-
def _get_font(self, font: str | int) -> FT2Font:
348-
if font in self.fontmap:
349-
basename = self.fontmap[font]
350-
else:
351-
# NOTE: An int is only passed by subclasses which have placed int keys into
352-
# `self.fontmap`, so we must cast this to confirm it to typing.
353-
basename = T.cast(str, font)
347+
def _get_font(self, font: str) -> FT2Font:
348+
basename = self.fontmap.get(font, font)
354349
cached_font = self._fonts.get(basename)
355350
if cached_font is None and os.path.exists(basename):
356351
cached_font = get_font(basename)
@@ -580,12 +575,13 @@ def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlag
580575
# include STIX sized alternatives for glyphs if fallback is STIX
581576
if isinstance(self._fallback_font, StixFonts):
582577
stixsizedaltfonts = {
583-
0: 'STIXGeneral',
584-
1: 'STIXSizeOneSym',
585-
2: 'STIXSizeTwoSym',
586-
3: 'STIXSizeThreeSym',
587-
4: 'STIXSizeFourSym',
588-
5: 'STIXSizeFiveSym'}
578+
'0': 'STIXGeneral',
579+
'1': 'STIXSizeOneSym',
580+
'2': 'STIXSizeTwoSym',
581+
'3': 'STIXSizeThreeSym',
582+
'4': 'STIXSizeFourSym',
583+
'5': 'STIXSizeFiveSym',
584+
}
589585

590586
for size, name in stixsizedaltfonts.items():
591587
fullpath = findfont(name)
@@ -643,7 +639,7 @@ def _get_glyph(self, fontname: str, font_class: str,
643639

644640
g = self._fallback_font._get_glyph(fontname, font_class, sym)
645641
family = g[0].family_name
646-
if family in list(BakomaFonts._fontmap.values()):
642+
if family in BakomaFonts._fontmap.values():
647643
family = "Computer Modern"
648644
_log.info("Substituting symbol %s from %s", sym, family)
649645
return g
@@ -664,13 +660,12 @@ def _get_glyph(self, fontname: str, font_class: str,
664660
def get_sized_alternatives_for_symbol(self, fontname: str,
665661
sym: str) -> list[tuple[str, str]]:
666662
if self._fallback_font:
667-
return self._fallback_font.get_sized_alternatives_for_symbol(
668-
fontname, sym)
663+
return self._fallback_font.get_sized_alternatives_for_symbol(fontname, sym)
669664
return [(fontname, sym)]
670665

671666

672667
class DejaVuFonts(UnicodeFonts, metaclass=abc.ABCMeta):
673-
_fontmap: dict[str | int, str] = {}
668+
_fontmap: dict[str, str] = {}
674669

675670
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags):
676671
# This must come first so the backend's owner is set correctly
@@ -682,11 +677,11 @@ def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlag
682677
TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags)
683678
# Include Stix sized alternatives for glyphs
684679
self._fontmap.update({
685-
1: 'STIXSizeOneSym',
686-
2: 'STIXSizeTwoSym',
687-
3: 'STIXSizeThreeSym',
688-
4: 'STIXSizeFourSym',
689-
5: 'STIXSizeFiveSym',
680+
'1': 'STIXSizeOneSym',
681+
'2': 'STIXSizeTwoSym',
682+
'3': 'STIXSizeThreeSym',
683+
'4': 'STIXSizeFourSym',
684+
'5': 'STIXSizeFiveSym',
690685
})
691686
for key, name in self._fontmap.items():
692687
fullpath = findfont(name)
@@ -724,7 +719,7 @@ class DejaVuSerifFonts(DejaVuFonts):
724719
'sf': 'DejaVu Sans',
725720
'tt': 'DejaVu Sans Mono',
726721
'ex': 'DejaVu Serif Display',
727-
0: 'DejaVu Serif',
722+
'0': 'DejaVu Serif',
728723
}
729724

730725

@@ -742,7 +737,7 @@ class DejaVuSansFonts(DejaVuFonts):
742737
'sf': 'DejaVu Sans',
743738
'tt': 'DejaVu Sans Mono',
744739
'ex': 'DejaVu Sans Display',
745-
0: 'DejaVu Sans',
740+
'0': 'DejaVu Sans',
746741
}
747742

748743

@@ -758,20 +753,20 @@ class StixFonts(UnicodeFonts):
758753
759754
- handles sized alternative characters for the STIXSizeX fonts.
760755
"""
761-
_fontmap: dict[str | int, str] = {
756+
_fontmap = {
762757
'rm': 'STIXGeneral',
763758
'it': 'STIXGeneral:italic',
764759
'bf': 'STIXGeneral:weight=bold',
765760
'bfit': 'STIXGeneral:italic:bold',
766761
'nonunirm': 'STIXNonUnicode',
767762
'nonuniit': 'STIXNonUnicode:italic',
768763
'nonunibf': 'STIXNonUnicode:weight=bold',
769-
0: 'STIXGeneral',
770-
1: 'STIXSizeOneSym',
771-
2: 'STIXSizeTwoSym',
772-
3: 'STIXSizeThreeSym',
773-
4: 'STIXSizeFourSym',
774-
5: 'STIXSizeFiveSym',
764+
'0': 'STIXGeneral',
765+
'1': 'STIXSizeOneSym',
766+
'2': 'STIXSizeTwoSym',
767+
'3': 'STIXSizeThreeSym',
768+
'4': 'STIXSizeFourSym',
769+
'5': 'STIXSizeFiveSym',
775770
}
776771
_fallback_font = None
777772
_sans = False
@@ -838,10 +833,8 @@ def _map_virtual_font(self, fontname: str, font_class: str,
838833
return fontname, uniindex
839834

840835
@functools.cache
841-
def get_sized_alternatives_for_symbol( # type: ignore[override]
842-
self,
843-
fontname: str,
844-
sym: str) -> list[tuple[str, str]] | list[tuple[int, str]]:
836+
def get_sized_alternatives_for_symbol(self, fontname: str,
837+
sym: str) -> list[tuple[str, str]]:
845838
fixes = {
846839
'\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']',
847840
'<': '\N{MATHEMATICAL LEFT ANGLE BRACKET}',
@@ -852,8 +845,8 @@ def get_sized_alternatives_for_symbol( # type: ignore[override]
852845
uniindex = get_unicode_index(sym)
853846
except ValueError:
854847
return [(fontname, sym)]
855-
alternatives = [(i, chr(uniindex)) for i in range(6)
856-
if self._get_font(i).get_char_index(uniindex) != 0]
848+
alternatives = [(str(i), chr(uniindex)) for i in range(6)
849+
if self._get_font(str(i)).get_char_index(uniindex) != 0]
857850
# The largest size of the radical symbol in STIX has incorrect
858851
# metrics that cause it to be disconnected from the stem.
859852
if sym == r'\__sqrt__':
@@ -1171,7 +1164,7 @@ def __init__(self, elements: T.Sequence[Node]):
11711164
self.glue_sign = 0 # 0: normal, -1: shrinking, 1: stretching
11721165
self.glue_order = 0 # The order of infinity (0 - 3) for the glue
11731166

1174-
def __repr__(self):
1167+
def __repr__(self) -> str:
11751168
return "{}<w={:.02f} h={:.02f} d={:.02f} s={:.02f}>[{}]".format(
11761169
super().__repr__(),
11771170
self.width, self.height,
@@ -1542,7 +1535,7 @@ def __init__(self, c: str, height: float, depth: float, state: ParserState,
15421535
break
15431536

15441537
shift = 0.0
1545-
if state.font != 0 or len(alternatives) == 1:
1538+
if state.font != '0' or len(alternatives) == 1:
15461539
if factor is None:
15471540
factor = target_total / (char.height + char.depth)
15481541
state.fontsize *= factor
@@ -2528,7 +2521,7 @@ def subsuper(self, s: str, loc: int, toks: ParseResults) -> T.Any:
25282521
# Handle regular sub/superscripts
25292522
consts = _get_font_constant_set(state)
25302523
lc_height = last_char.height
2531-
lc_baseline = 0
2524+
lc_baseline = 0.0
25322525
if self.is_dropsub(last_char):
25332526
lc_baseline = last_char.depth
25342527

0 commit comments

Comments
 (0)