Reduce use of py23

This commit is contained in:
Nikolaus Waxweiler 2019-09-09 22:24:59 +01:00 committed by Nikolaus Waxweiler
parent 14bb52a616
commit 0f5b6e2e83
9 changed files with 105 additions and 125 deletions

View File

@ -15,7 +15,7 @@ import fs.osfs
import fs.zipfs
import fs.tempfs
import fs.tools
from fontTools.misc.py23 import basestring, unicode, tounicode
from fontTools.misc.py23 import tostr
from fontTools.misc import plistlib
from fontTools.ufoLib.validators import *
from fontTools.ufoLib.filenames import userNameToFileName
@ -205,7 +205,7 @@ class UFOReader(_UFOBaseIO):
if hasattr(path, "__fspath__"): # support os.PathLike objects
path = path.__fspath__()
if isinstance(path, basestring):
if isinstance(path, str):
structure = _sniffFileStructure(path)
try:
if structure is UFOFileStructure.ZIP:
@ -252,7 +252,7 @@ class UFOReader(_UFOBaseIO):
path = filesystem.getsyspath("/")
except fs.errors.NoSysPath:
# network or in-memory FS may not map to the local one
path = unicode(filesystem)
path = str(filesystem)
# when user passed an already initialized fs instance, it is her
# responsibility to close it, thus UFOReader.close/__exit__ are no-op
self._shouldClose = False
@ -324,12 +324,12 @@ class UFOReader(_UFOBaseIO):
if not isinstance(groups, dict):
raise UFOLibError(invalidFormatMessage)
for groupName, glyphList in groups.items():
if not isinstance(groupName, basestring):
if not isinstance(groupName, str):
raise UFOLibError(invalidFormatMessage)
elif not isinstance(glyphList, list):
raise UFOLibError(invalidFormatMessage)
for glyphName in glyphList:
if not isinstance(glyphName, basestring):
if not isinstance(glyphName, str):
raise UFOLibError(invalidFormatMessage)
self._upConvertedKerningData = dict(
kerning={},
@ -366,7 +366,7 @@ class UFOReader(_UFOBaseIO):
The path must be relative to the UFO path.
Returns None if the file does not exist.
By default the file is opened in binary mode (reads bytes).
If encoding is passed, the file is opened in text mode (reads unicode).
If encoding is passed, the file is opened in text mode (reads str).
Note: The caller is responsible for closing the open file.
"""
@ -572,7 +572,7 @@ class UFOReader(_UFOBaseIO):
def readFeatures(self):
"""
Read features.fea. Return a unicode string.
Read features.fea. Return a string.
The returned string is empty if the file is missing.
"""
try:
@ -672,7 +672,7 @@ class UFOReader(_UFOBaseIO):
def getCharacterMapping(self, layerName=None, validate=None):
"""
Return a dictionary that maps unicode values (ints) to
Return a dictionary that maps str values (ints) to
lists of glyph names.
"""
if validate is None:
@ -829,7 +829,7 @@ class UFOWriter(UFOReader):
if hasattr(path, "__fspath__"): # support os.PathLike objects
path = path.__fspath__()
if isinstance(path, basestring):
if isinstance(path, str):
# normalize path by removing trailing or double slashes
path = os.path.normpath(path)
havePreviousFile = os.path.exists(path)
@ -909,7 +909,7 @@ class UFOWriter(UFOReader):
path = filesystem.getsyspath("/")
except fs.errors.NoSysPath:
# network or in-memory FS may not map to the local one
path = unicode(filesystem)
path = str(filesystem)
# if passed an FS object, always use 'package' structure
if structure and structure is not UFOFileStructure.PACKAGE:
import warnings
@ -1241,9 +1241,9 @@ class UFOWriter(UFOReader):
raise UFOLibError(invalidFormatMessage)
if not len(pair) == 2:
raise UFOLibError(invalidFormatMessage)
if not isinstance(pair[0], basestring):
if not isinstance(pair[0], str):
raise UFOLibError(invalidFormatMessage)
if not isinstance(pair[1], basestring):
if not isinstance(pair[1], str):
raise UFOLibError(invalidFormatMessage)
if not isinstance(value, numberTypes):
raise UFOLibError(invalidFormatMessage)
@ -1301,7 +1301,7 @@ class UFOWriter(UFOReader):
if self._formatVersion == 1:
raise UFOLibError("features.fea is not allowed in UFO Format Version 1.")
if validate:
if not isinstance(features, basestring):
if not isinstance(features, str):
raise UFOLibError("The features are not text.")
if features:
self.writeBytesToPath(FEATURES_FILENAME, features.encode("utf8"))
@ -1325,7 +1325,7 @@ class UFOWriter(UFOReader):
if layerName is None:
layerName = DEFAULT_LAYER_NAME
else:
layerName = tounicode(layerName)
layerName = tostr(layerName)
newOrder.append(layerName)
layerOrder = newOrder
else:
@ -1439,9 +1439,9 @@ class UFOWriter(UFOReader):
# not caching this could be slightly expensive,
# but caching it will be cumbersome
existing = {d.lower() for d in self.layerContents.values()}
if not isinstance(layerName, unicode):
if not isinstance(layerName, str):
try:
layerName = unicode(layerName)
layerName = str(layerName)
except UnicodeDecodeError:
raise UFOLibError("The specified layer name is not a Unicode string.")
directory = userNameToFileName(layerName, existing=existing, prefix="glyphs.")
@ -1587,7 +1587,7 @@ UFOReaderWriter = UFOWriter
def _sniffFileStructure(ufo_path):
"""Return UFOFileStructure.ZIP if the UFO at path 'ufo_path' (basestring)
"""Return UFOFileStructure.ZIP if the UFO at path 'ufo_path' (str)
is a zip file, else return UFOFileStructure.PACKAGE if 'ufo_path' is a
directory.
Raise UFOLibError if it is a file with unknown structure, or if the path
@ -1775,23 +1775,23 @@ fontInfoAttributesVersion1 = {
}
fontInfoAttributesVersion2ValueData = {
"familyName" : dict(type=basestring),
"styleName" : dict(type=basestring),
"styleMapFamilyName" : dict(type=basestring),
"styleMapStyleName" : dict(type=basestring, valueValidator=fontInfoStyleMapStyleNameValidator),
"familyName" : dict(type=str),
"styleName" : dict(type=str),
"styleMapFamilyName" : dict(type=str),
"styleMapStyleName" : dict(type=str, valueValidator=fontInfoStyleMapStyleNameValidator),
"versionMajor" : dict(type=int),
"versionMinor" : dict(type=int),
"year" : dict(type=int),
"copyright" : dict(type=basestring),
"trademark" : dict(type=basestring),
"copyright" : dict(type=str),
"trademark" : dict(type=str),
"unitsPerEm" : dict(type=(int, float)),
"descender" : dict(type=(int, float)),
"xHeight" : dict(type=(int, float)),
"capHeight" : dict(type=(int, float)),
"ascender" : dict(type=(int, float)),
"italicAngle" : dict(type=(float, int)),
"note" : dict(type=basestring),
"openTypeHeadCreated" : dict(type=basestring, valueValidator=fontInfoOpenTypeHeadCreatedValidator),
"note" : dict(type=str),
"openTypeHeadCreated" : dict(type=str, valueValidator=fontInfoOpenTypeHeadCreatedValidator),
"openTypeHeadLowestRecPPEM" : dict(type=(int, float)),
"openTypeHeadFlags" : dict(type="integerList", valueValidator=genericIntListValidator, valueOptions=fontInfoOpenTypeHeadFlagsOptions),
"openTypeHheaAscender" : dict(type=(int, float)),
@ -1800,25 +1800,25 @@ fontInfoAttributesVersion2ValueData = {
"openTypeHheaCaretSlopeRise" : dict(type=int),
"openTypeHheaCaretSlopeRun" : dict(type=int),
"openTypeHheaCaretOffset" : dict(type=(int, float)),
"openTypeNameDesigner" : dict(type=basestring),
"openTypeNameDesignerURL" : dict(type=basestring),
"openTypeNameManufacturer" : dict(type=basestring),
"openTypeNameManufacturerURL" : dict(type=basestring),
"openTypeNameLicense" : dict(type=basestring),
"openTypeNameLicenseURL" : dict(type=basestring),
"openTypeNameVersion" : dict(type=basestring),
"openTypeNameUniqueID" : dict(type=basestring),
"openTypeNameDescription" : dict(type=basestring),
"openTypeNamePreferredFamilyName" : dict(type=basestring),
"openTypeNamePreferredSubfamilyName" : dict(type=basestring),
"openTypeNameCompatibleFullName" : dict(type=basestring),
"openTypeNameSampleText" : dict(type=basestring),
"openTypeNameWWSFamilyName" : dict(type=basestring),
"openTypeNameWWSSubfamilyName" : dict(type=basestring),
"openTypeNameDesigner" : dict(type=str),
"openTypeNameDesignerURL" : dict(type=str),
"openTypeNameManufacturer" : dict(type=str),
"openTypeNameManufacturerURL" : dict(type=str),
"openTypeNameLicense" : dict(type=str),
"openTypeNameLicenseURL" : dict(type=str),
"openTypeNameVersion" : dict(type=str),
"openTypeNameUniqueID" : dict(type=str),
"openTypeNameDescription" : dict(type=str),
"openTypeNamePreferredFamilyName" : dict(type=str),
"openTypeNamePreferredSubfamilyName" : dict(type=str),
"openTypeNameCompatibleFullName" : dict(type=str),
"openTypeNameSampleText" : dict(type=str),
"openTypeNameWWSFamilyName" : dict(type=str),
"openTypeNameWWSSubfamilyName" : dict(type=str),
"openTypeOS2WidthClass" : dict(type=int, valueValidator=fontInfoOpenTypeOS2WidthClassValidator),
"openTypeOS2WeightClass" : dict(type=int, valueValidator=fontInfoOpenTypeOS2WeightClassValidator),
"openTypeOS2Selection" : dict(type="integerList", valueValidator=genericIntListValidator, valueOptions=fontInfoOpenTypeOS2SelectionOptions),
"openTypeOS2VendorID" : dict(type=basestring),
"openTypeOS2VendorID" : dict(type=str),
"openTypeOS2Panose" : dict(type="integerList", valueValidator=fontInfoVersion2OpenTypeOS2PanoseValidator),
"openTypeOS2FamilyClass" : dict(type="integerList", valueValidator=fontInfoOpenTypeOS2FamilyClassValidator),
"openTypeOS2UnicodeRanges" : dict(type="integerList", valueValidator=genericIntListValidator, valueOptions=fontInfoOpenTypeOS2UnicodeRangesOptions),
@ -1845,8 +1845,8 @@ fontInfoAttributesVersion2ValueData = {
"openTypeVheaCaretSlopeRise" : dict(type=int),
"openTypeVheaCaretSlopeRun" : dict(type=int),
"openTypeVheaCaretOffset" : dict(type=(int, float)),
"postscriptFontName" : dict(type=basestring),
"postscriptFullName" : dict(type=basestring),
"postscriptFontName" : dict(type=str),
"postscriptFullName" : dict(type=str),
"postscriptSlantAngle" : dict(type=(float, int)),
"postscriptUniqueID" : dict(type=int),
"postscriptUnderlineThickness" : dict(type=(int, float)),
@ -1864,11 +1864,11 @@ fontInfoAttributesVersion2ValueData = {
"postscriptForceBold" : dict(type=bool),
"postscriptDefaultWidthX" : dict(type=(int, float)),
"postscriptNominalWidthX" : dict(type=(int, float)),
"postscriptWeightName" : dict(type=basestring),
"postscriptDefaultCharacter" : dict(type=basestring),
"postscriptWeightName" : dict(type=str),
"postscriptDefaultCharacter" : dict(type=str),
"postscriptWindowsCharacterSet" : dict(type=int, valueValidator=fontInfoPostscriptWindowsCharacterSetValidator),
"macintoshFONDFamilyID" : dict(type=int),
"macintoshFONDName" : dict(type=basestring),
"macintoshFONDName" : dict(type=str),
}
fontInfoAttributesVersion2 = set(fontInfoAttributesVersion2ValueData.keys())

View File

@ -2,8 +2,6 @@
User name to file name conversion.
This was taken form the UFO 3 spec.
"""
from fontTools.misc.py23 import basestring, unicode
illegalCharacters = r"\" * + / : < > ? [ \ ] | \0".split(" ")
illegalCharacters += [chr(i) for i in range(1, 32)]
@ -67,9 +65,9 @@ def userNameToFileName(userName, existing=[], prefix="", suffix=""):
>>> userNameToFileName("alt.con") == "alt._con"
True
"""
# the incoming name must be a unicode string
if not isinstance(userName, unicode):
raise ValueError("The value for userName must be a unicode string.")
# the incoming name must be a string
if not isinstance(userName, str):
raise ValueError("The value for userName must be a string.")
# establish the prefix and suffix lengths
prefixLength = len(prefix)
suffixLength = len(suffix)

View File

@ -17,7 +17,7 @@ import fs.base
import fs.errors
import fs.osfs
import fs.path
from fontTools.misc.py23 import basestring, unicode, tobytes, tounicode
from fontTools.misc.py23 import tobytes, tostr
from fontTools.misc import plistlib
from fontTools.pens.pointPen import AbstractPointPen, PointToSegmentPen
from fontTools.ufoLib.errors import GlifLibError
@ -127,7 +127,7 @@ class GlyphSet(_UFOBaseIO):
"""
if ufoFormatVersion not in supportedUFOFormatVersions:
raise GlifLibError("Unsupported UFO format version: %s" % ufoFormatVersion)
if isinstance(path, basestring):
if isinstance(path, str):
try:
filesystem = fs.osfs.OSFS(path)
except fs.errors.CreateFailed:
@ -149,7 +149,7 @@ class GlyphSet(_UFOBaseIO):
path = filesystem.getsyspath("/")
except fs.errors.NoSysPath:
# network or in-memory FS may not map to the local one
path = unicode(filesystem)
path = str(filesystem)
# 'dirName' is kept for backward compatibility only, but it's DEPRECATED
# as it's not guaranteed that it maps to an existing OSFS directory.
# Client could use the FS api via the `self.fs` attribute instead.
@ -185,9 +185,9 @@ class GlyphSet(_UFOBaseIO):
invalidFormat = True
else:
for name, fileName in contents.items():
if not isinstance(name, basestring):
if not isinstance(name, str):
invalidFormat = True
if not isinstance(fileName, basestring):
if not isinstance(fileName, str):
invalidFormat = True
elif not self.fs.exists(fileName):
raise GlifLibError(
@ -521,9 +521,9 @@ def glyphNameToFileName(glyphName, existingFileNames):
"""
if existingFileNames is None:
existingFileNames = []
if not isinstance(glyphName, unicode):
if not isinstance(glyphName, str):
try:
new = unicode(glyphName)
new = str(glyphName)
glyphName = new
except UnicodeDecodeError:
pass
@ -576,7 +576,7 @@ def _writeGlyphToBytes(
formatVersion=2, validate=True):
"""Return .glif data for a glyph as a UTF-8 encoded bytes string."""
# start
if validate and not isinstance(glyphName, basestring):
if validate and not isinstance(glyphName, str):
raise GlifLibError("The glyph name is not properly formatted.")
if validate and len(glyphName) == 0:
raise GlifLibError("The glyph name is empty.")
@ -695,12 +695,12 @@ def _writeUnicodes(glyphObject, element, validate):
def _writeNote(glyphObject, element, validate):
note = getattr(glyphObject, "note", None)
if validate and not isinstance(note, basestring):
raise GlifLibError("note attribute must be str or unicode")
if validate and not isinstance(note, str):
raise GlifLibError("note attribute must be str")
note = note.strip()
note = "\n" + note + "\n"
# ensure text is unicode, if it's bytes decode as ASCII
etree.SubElement(element, "note").text = tounicode(note)
# ensure text is str, if it's bytes decode as ASCII
etree.SubElement(element, "note").text = note
def _writeImage(glyphObject, element, validate):
image = getattr(glyphObject, "image", None)
@ -805,7 +805,7 @@ def _writeLib(glyphObject, element, validate):
# -----------------------
layerInfoVersion3ValueData = {
"color" : dict(type=basestring, valueValidator=colorValidator),
"color" : dict(type=str, valueValidator=colorValidator),
"lib" : dict(type=dict, valueValidator=genericTypeValidator)
}

View File

@ -12,7 +12,7 @@ from fontTools.ufoLib.utils import deprecated
@deprecated("Use 'fontTools.misc.plistlib.load' instead")
def readPlist(path_or_file):
did_open = False
if isinstance(path_or_file, basestring):
if isinstance(path_or_file, str):
path_or_file = open(path_or_file, "rb")
did_open = True
try:
@ -25,7 +25,7 @@ def readPlist(path_or_file):
@deprecated("Use 'fontTools.misc.plistlib.dump' instead")
def writePlist(value, path_or_file):
did_open = False
if isinstance(path_or_file, basestring):
if isinstance(path_or_file, str):
path_or_file = open(path_or_file, "wb")
did_open = True
try:

View File

@ -5,12 +5,7 @@ from io import open
import fs.base
import fs.osfs
try:
from collections.abc import Mapping # python >= 3.3
except ImportError:
from collections import Mapping
from fontTools.misc.py23 import basestring
from collections.abc import Mapping
from fontTools.ufoLib.utils import integerTypes, numberTypes
@ -142,7 +137,7 @@ def fontInfoOpenTypeHeadCreatedValidator(value):
Version 2+.
"""
# format: 0000/00/00 00:00:00
if not isinstance(value, basestring):
if not isinstance(value, str):
return False
# basic formatting
if not len(value) == 19:
@ -202,7 +197,7 @@ def fontInfoOpenTypeNameRecordsValidator(value):
"""
if not isinstance(value, list):
return False
dictPrototype = dict(nameID=(int, True), platformID=(int, True), encodingID=(int, True), languageID=(int, True), string=(basestring, True))
dictPrototype = dict(nameID=(int, True), platformID=(int, True), encodingID=(int, True), languageID=(int, True), string=(str, True))
for nameRecord in value:
if not genericDictValidator(nameRecord, dictPrototype):
return False
@ -334,7 +329,7 @@ def fontInfoWOFFMetadataUniqueIDValidator(value):
"""
Version 3+.
"""
dictPrototype = dict(id=(basestring, True))
dictPrototype = dict(id=(str, True))
if not genericDictValidator(value, dictPrototype):
return False
return True
@ -343,7 +338,7 @@ def fontInfoWOFFMetadataVendorValidator(value):
"""
Version 3+.
"""
dictPrototype = {"name" : (basestring, True), "url" : (basestring, False), "dir" : (basestring, False), "class" : (basestring, False)}
dictPrototype = {"name" : (str, True), "url" : (str, False), "dir" : (str, False), "class" : (str, False)}
if not genericDictValidator(value, dictPrototype):
return False
if "dir" in value and value.get("dir") not in ("ltr", "rtl"):
@ -359,7 +354,7 @@ def fontInfoWOFFMetadataCreditsValidator(value):
return False
if not len(value["credits"]):
return False
dictPrototype = {"name" : (basestring, True), "url" : (basestring, False), "role" : (basestring, False), "dir" : (basestring, False), "class" : (basestring, False)}
dictPrototype = {"name" : (str, True), "url" : (str, False), "role" : (str, False), "dir" : (str, False), "class" : (str, False)}
for credit in value["credits"]:
if not genericDictValidator(credit, dictPrototype):
return False
@ -371,7 +366,7 @@ def fontInfoWOFFMetadataDescriptionValidator(value):
"""
Version 3+.
"""
dictPrototype = dict(url=(basestring, False), text=(list, True))
dictPrototype = dict(url=(str, False), text=(list, True))
if not genericDictValidator(value, dictPrototype):
return False
for text in value["text"]:
@ -383,7 +378,7 @@ def fontInfoWOFFMetadataLicenseValidator(value):
"""
Version 3+.
"""
dictPrototype = dict(url=(basestring, False), text=(list, False), id=(basestring, False))
dictPrototype = dict(url=(str, False), text=(list, False), id=(str, False))
if not genericDictValidator(value, dictPrototype):
return False
if "text" in value:
@ -420,7 +415,7 @@ def fontInfoWOFFMetadataLicenseeValidator(value):
"""
Version 3+.
"""
dictPrototype = {"name" : (basestring, True), "dir" : (basestring, False), "class" : (basestring, False)}
dictPrototype = {"name" : (str, True), "dir" : (str, False), "class" : (str, False)}
if not genericDictValidator(value, dictPrototype):
return False
if "dir" in value and value.get("dir") not in ("ltr", "rtl"):
@ -431,7 +426,7 @@ def fontInfoWOFFMetadataTextValue(value):
"""
Version 3+.
"""
dictPrototype = {"text" : (basestring, True), "language" : (basestring, False), "dir" : (basestring, False), "class" : (basestring, False)}
dictPrototype = {"text" : (str, True), "language" : (str, False), "dir" : (str, False), "class" : (str, False)}
if not genericDictValidator(value, dictPrototype):
return False
if "dir" in value and value.get("dir") not in ("ltr", "rtl"):
@ -455,7 +450,7 @@ def fontInfoWOFFMetadataExtensionValidator(value):
"""
Version 3+.
"""
dictPrototype = dict(names=(list, False), items=(list, True), id=(basestring, False))
dictPrototype = dict(names=(list, False), items=(list, True), id=(str, False))
if not genericDictValidator(value, dictPrototype):
return False
if "names" in value:
@ -471,7 +466,7 @@ def fontInfoWOFFMetadataExtensionItemValidator(value):
"""
Version 3+.
"""
dictPrototype = dict(id=(basestring, False), names=(list, True), values=(list, True))
dictPrototype = dict(id=(str, False), names=(list, True), values=(list, True))
if not genericDictValidator(value, dictPrototype):
return False
for name in value["names"]:
@ -486,7 +481,7 @@ def fontInfoWOFFMetadataExtensionNameValidator(value):
"""
Version 3+.
"""
dictPrototype = {"text" : (basestring, True), "language" : (basestring, False), "dir" : (basestring, False), "class" : (basestring, False)}
dictPrototype = {"text" : (str, True), "language" : (str, False), "dir" : (str, False), "class" : (str, False)}
if not genericDictValidator(value, dictPrototype):
return False
if "dir" in value and value.get("dir") not in ("ltr", "rtl"):
@ -497,7 +492,7 @@ def fontInfoWOFFMetadataExtensionValueValidator(value):
"""
Version 3+.
"""
dictPrototype = {"text" : (basestring, True), "language" : (basestring, False), "dir" : (basestring, False), "class" : (basestring, False)}
dictPrototype = {"text" : (str, True), "language" : (str, False), "dir" : (str, False), "class" : (str, False)}
if not genericDictValidator(value, dictPrototype):
return False
if "dir" in value and value.get("dir") not in ("ltr", "rtl"):
@ -528,7 +523,7 @@ def guidelinesValidator(value, identifiers=None):
_guidelineDictPrototype = dict(
x=((int, float), False), y=((int, float), False), angle=((int, float), False),
name=(basestring, False), color=(basestring, False), identifier=(basestring, False)
name=(str, False), color=(str, False), identifier=(str, False)
)
def guidelineValidator(value):
@ -590,8 +585,8 @@ def anchorsValidator(value, identifiers=None):
_anchorDictPrototype = dict(
x=((int, float), False), y=((int, float), False),
name=(basestring, False), color=(basestring, False),
identifier=(basestring, False)
name=(str, False), color=(str, False),
identifier=(str, False)
)
def anchorValidator(value):
@ -632,7 +627,7 @@ def identifierValidator(value):
"""
validCharactersMin = 0x20
validCharactersMax = 0x7E
if not isinstance(value, basestring):
if not isinstance(value, str):
return False
if not value:
return False
@ -691,7 +686,7 @@ def colorValidator(value):
>>> colorValidator("1, 1, 1, 1")
True
"""
if not isinstance(value, basestring):
if not isinstance(value, str):
return False
parts = value.split(",")
if len(parts) != 4:
@ -725,11 +720,11 @@ def colorValidator(value):
pngSignature = b"\x89PNG\r\n\x1a\n"
_imageDictPrototype = dict(
fileName=(basestring, True),
fileName=(str, True),
xScale=((int, float), False), xyScale=((int, float), False),
yxScale=((int, float), False), yScale=((int, float), False),
xOffset=((int, float), False), yOffset=((int, float), False),
color=(basestring, False)
color=(str, False)
)
def imageValidator(value):
@ -796,7 +791,7 @@ def layerContentsValidator(value, ufoPathOrFileSystem):
if not len(entry) == 2:
return False, bogusFileMessage
for i in entry:
if not isinstance(i, basestring):
if not isinstance(i, str):
return False, bogusFileMessage
layerName, directoryName = entry
# check directory naming
@ -880,7 +875,7 @@ def groupsValidator(value):
firstSideMapping = {}
secondSideMapping = {}
for groupName, glyphList in value.items():
if not isinstance(groupName, (basestring)):
if not isinstance(groupName, (str)):
return False, bogusFormatMessage
if not isinstance(glyphList, (list, tuple)):
return False, bogusFormatMessage
@ -898,7 +893,7 @@ def groupsValidator(value):
else:
d = secondSideMapping
for glyphName in glyphList:
if not isinstance(glyphName, basestring):
if not isinstance(glyphName, str):
return False, "The group data %s contains an invalid member." % groupName
if glyphName in d:
return False, "The glyph \"%s\" occurs in too many kerning groups." % glyphName
@ -936,12 +931,12 @@ def kerningValidator(data):
if not isinstance(data, Mapping):
return False, bogusFormatMessage
for first, secondDict in data.items():
if not isinstance(first, basestring):
if not isinstance(first, str):
return False, bogusFormatMessage
elif not isinstance(secondDict, Mapping):
return False, bogusFormatMessage
for second, value in secondDict.items():
if not isinstance(second, basestring):
if not isinstance(second, str):
return False, bogusFormatMessage
elif not isinstance(value, numberTypes):
return False, bogusFormatMessage
@ -982,7 +977,7 @@ def fontLibValidator(value):
>>> valid
False
>>> print(msg)
The lib key is not properly formatted: expected basestring, found int: 1
The lib key is not properly formatted: expected str, found int: 1
>>> lib = {"public.glyphOrder" : "hello"}
>>> valid, msg = fontLibValidator(lib)
@ -996,15 +991,15 @@ def fontLibValidator(value):
>>> valid
False
>>> print(msg) # doctest: +ELLIPSIS
public.glyphOrder is not properly formatted: expected basestring,...
public.glyphOrder is not properly formatted: expected str,...
"""
if not isDictEnough(value):
reason = "expected a dictionary, found %s" % type(value).__name__
return False, _bogusLibFormatMessage % reason
for key, value in value.items():
if not isinstance(key, basestring):
if not isinstance(key, str):
return False, (
"The lib key is not properly formatted: expected basestring, found %s: %r" %
"The lib key is not properly formatted: expected str, found %s: %r" %
(type(key).__name__, key))
# public.glyphOrder
if key == "public.glyphOrder":
@ -1013,8 +1008,8 @@ def fontLibValidator(value):
reason = "expected list or tuple, found %s" % type(value).__name__
return False, bogusGlyphOrderMessage % reason
for glyphName in value:
if not isinstance(glyphName, basestring):
reason = "expected basestring, found %s" % type(glyphName).__name__
if not isinstance(glyphName, str):
reason = "expected str, found %s" % type(glyphName).__name__
return False, bogusGlyphOrderMessage % reason
return True, None
@ -1050,7 +1045,7 @@ def glyphLibValidator(value):
reason = "expected a dictionary, found %s" % type(value).__name__
return False, _bogusLibFormatMessage % reason
for key, value in value.items():
if not isinstance(key, basestring):
if not isinstance(key, str):
reason = "key (%s) should be a string" % key
return False, _bogusLibFormatMessage % reason
# public.markColor

View File

@ -3,10 +3,6 @@ from fontTools.ufoLib.glifLib import GlifLibError, readGlyphFromString, writeGly
from .testSupport import Glyph, stripText
from itertools import islice
try:
basestring
except NameError:
basestring = str
# ----------
# Test Cases
# ----------
@ -14,9 +10,9 @@ except NameError:
class TestGLIF1(unittest.TestCase):
def assertEqual(self, first, second, msg=None):
if isinstance(first, basestring):
if isinstance(first, str):
first = stripText(first)
if isinstance(second, basestring):
if isinstance(second, str):
second = stripText(second)
return super().assertEqual(first, second, msg=msg)

View File

@ -3,10 +3,6 @@ from fontTools.ufoLib.glifLib import GlifLibError, readGlyphFromString, writeGly
from .testSupport import Glyph, stripText
from itertools import islice
try:
basestring
except NameError:
basestring = str
# ----------
# Test Cases
# ----------
@ -14,9 +10,9 @@ except NameError:
class TestGLIF2(unittest.TestCase):
def assertEqual(self, first, second, msg=None):
if isinstance(first, basestring):
if isinstance(first, str):
first = stripText(first)
if isinstance(second, basestring):
if isinstance(second, str):
second = stripText(second)
return super().assertEqual(first, second, msg=msg)

View File

@ -3,7 +3,6 @@ import shutil
import unittest
import tempfile
from io import open
from fontTools.misc.py23 import unicode
from fontTools.ufoLib import UFOReader, UFOWriter, UFOLibError
from fontTools.ufoLib.glifLib import GlifLibError
from fontTools.misc import plistlib
@ -4151,7 +4150,7 @@ class UFO3WriteLayersTestCase(unittest.TestCase):
]
self.assertEqual(expected, result)
for layerName, directory in result:
assert isinstance(layerName, unicode)
assert isinstance(layerName, str)
# -----
# /data

View File

@ -3,10 +3,6 @@
import os
from fontTools.ufoLib.utils import numberTypes
try:
basestring
except NameError:
basestring = str
def getDemoFontPath():
"""Return the path to Data/DemoFont.ufo/."""
@ -102,7 +98,7 @@ def _dictToString(d):
value = _tupleToString(value)
elif isinstance(value, numberTypes):
value = repr(value)
elif isinstance(value, basestring):
elif isinstance(value, str):
value = "\"%s\"" % value
text.append(f"{key} : {value}")
if not text:
@ -120,7 +116,7 @@ def _listToString(l):
value = _tupleToString(value)
elif isinstance(value, numberTypes):
value = repr(value)
elif isinstance(value, basestring):
elif isinstance(value, str):
value = "\"%s\"" % value
text.append(value)
if not text:
@ -138,7 +134,7 @@ def _tupleToString(t):
value = _tupleToString(value)
elif isinstance(value, numberTypes):
value = repr(value)
elif isinstance(value, basestring):
elif isinstance(value, str):
value = "\"%s\"" % value
text.append(value)
if not text: