API Reference

Core Objects

Font

class ufoLib2.objects.Font(path: Optional[Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]] = None, *, layers: ufoLib2.objects.layerSet.LayerSet = NOTHING, info: Union[ufoLib2.objects.info.Info, Mapping[str, Any]] = NOTHING, features: Union[ufoLib2.objects.features.Features, str] = NOTHING, groups: Dict[str, List[str]] = NOTHING, kerning: Dict[Tuple[str, str], float] = NOTHING, lib: Dict[str, Any] = NOTHING, data: Union[ufoLib2.objects.dataSet.DataSet, Mapping[str, Any]] = NOTHING, images: Union[ufoLib2.objects.imageSet.ImageSet, Mapping[str, Any]] = NOTHING, lazy: Optional[bool] = None, validate: bool = True)[source]

A data class representing a single Unified Font Object (UFO).

Font uses fontTools.ufoLib.UFOReader and fontTools.ufoLib.UFOWriter to read and write UFO data from and to disk. It will default to reading lazily, loading glyphs, data and images as they are accessed. Copying a font implicitly loads everything eagerly before.

The data model is formally specified at http://unifiedfontobject.org/versions/ufo3/index.html.

Parameters
  • path – The path to the UFO to load. The only positional parameter and a defcon-API-compatibility parameter. We recommend to use the Font.open() class method instead.

  • layers (LayerSet) – A mapping of layer names to Layer objects.

  • info (Info) – The font Info object.

  • features (Features) – The font Features object.

  • groups (Dict[str, List[str]]) – A mapping of group names to a list of glyph names.

  • kerning (Dict[Tuple[str, str], float]) – A mapping of a tuple of first and second kerning pair to a kerning value.

  • lib (Dict[str, Any]) – A mapping of keys to arbitrary values.

  • data (DataSet) – A mapping of data file paths to arbitrary data.

  • images (ImageSet) – A mapping of image file paths to arbitrary image data.

Behavior:

The Font object has some dict-like behavior for quick access to glyphs on the the default layer. For example, to get a glyph by name from the default layer:

glyph = font["aGlyphName"]

To iterate over all glyphs in the default layer:

for glyph in font:
    pass

To get the number of glyphs in the default layer:

glyphCount = len(font)

To find out if a font contains a particular glyph in the default layer by name:

exists = "aGlyphName" in font

To remove a glyph from the default layer by name:

del font["aGlyphName"]

To replace a glyph in the default layer with another Glyph object:

font["aGlyphName"] = otherGlyph

To copy a font:

import copy
fontCopy = copy.deepcopy(font)

Layers behave the same, for when you’re working on something other than the default layer.

addGlyph(glyph: ufoLib2.objects.glyph.Glyph)None[source]

Appends glyph object to the default layer unless its name is already taken.

Note

Call the method on the layer directly if you want to overwrite entries with the same name or append copies of the glyph.

appendGuideline(guideline: Union[ufoLib2.objects.guideline.Guideline, Mapping[str, Any]])None[source]

Appends a guideline to the list of the font’s global guidelines.

Creates the global guideline list unless it already exists.

Parameters

guideline – A Guideline object or a mapping for the Guideline constructor.

property bounds: Optional[ufoLib2.objects.misc.BoundingBox]

Returns the (xMin, yMin, xMax, yMax) bounding box of the default layer, taking the actual contours into account.

For defcon API compatibility only.

close()None[source]

Closes the UFOReader if it still exists to finalize any outstanding file operations.

property controlPointBounds: Optional[ufoLib2.objects.misc.BoundingBox]

Returns the (xMin, yMin, xMax, yMax) bounding box of the layer, taking only the control points into account.

For defcon API compatibility only.

data

A mapping of data file paths to arbitrary data.

Type

DataSet

features

The font Features object.

Type

Features

get(name: str, default: Optional[T] = None)Union[T, None, ufoLib2.objects.glyph.Glyph][source]

Return the Glyph object for name if it is present in the default layer, otherwise return default.

property glyphOrder: List[str]

The font’s glyph order.

See http://unifiedfontobject.org/versions/ufo3/lib.plist/#publicglyphorder for semantics.

Getter:

Return the font’s glyph order, if it is set in lib, or an empty list.

Note

The getter always returns a new list, modifications to it do not change the lib content.

Setter:

Sets the font’s glyph order. If value is None or an empty list, the glyph order key will be deleted from the lib if it exists.

groups

A mapping of group names to a list of glyph names.

Type

Dict[str, List[str]]

property guidelines: List[ufoLib2.objects.guideline.Guideline]

The font’s global guidelines.

Getter:

Returns the font’s global guidelines or an empty list.

Setter:
Appends the list of Guidelines to the global Guidelines.

XXX Should it replace them?

images

A mapping of image file paths to arbitrary image data.

Type

ImageSet

info

The font Info object.

Type

Info

kerning

A mapping of a tuple of first and second kerning pair to a kerning value.

Type

Dict[Tuple[str, str], float]

keys()KeysView[str][source]

Return a list of glyph names in the default layer.

layers

A mapping of layer names to Layer objects.

Type

LayerSet

lib

A mapping of keys to arbitrary values.

Type

Dict[str, Any]

newGlyph(name: str)ufoLib2.objects.glyph.Glyph[source]

Creates and returns new Glyph object in default layer with name.

newLayer(name: str, **kwargs: Any)ufoLib2.objects.layer.Layer[source]

Creates and returns a new Layer.

Parameters
  • name – The name of the new layer.

  • kwargs – The arguments passed to the Layer object constructor.

objectLib(object: ufoLib2.typing.HasIdentifier)Dict[str, Any][source]

Return the lib for an object with an identifier, as stored in a font’s lib.

If the object does not yet have an identifier, a new one is assigned to it. If the font lib does not yet contain the object’s lib, a new one is inserted and returned.

>>> from ufoLib2.objects import Font, Guideline
>>> font = Font()
>>> font.guidelines = [Guideline(x=100)]
>>> guideline_lib = font.objectLib(font.guidelines[0])
>>> guideline_lib["com.test.foo"] = 1234
>>> guideline_id = font.guidelines[0].identifier
>>> assert guideline_id is not None
>>> assert font.lib["public.objectLibs"][guideline_id] is guideline_lib
classmethod open(path: Union[str, bytes, os.PathLike[str], os.PathLike[bytes]], lazy: bool = True, validate: bool = True)Font[source]

Instantiates a new Font object from a path to a UFO.

Parameters
  • path – The path to the UFO to load.

  • lazy – If True, load glyphs, data files and images as they are accessed. If False, load everything up front.

  • validate – If True, enable UFO data model validation during loading. If False, load whatever is deserializable.

property path: Optional[Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]]

Return the path of the UFO, if it was set, or None.

classmethod read(reader: fontTools.ufoLib.UFOReader, lazy: bool = True)ufoLib2.objects.font.Font[source]

Instantiates a Font object from a fontTools.ufoLib.UFOReader.

Parameters
  • path – The path to the UFO to load.

  • lazy – If True, load glyphs, data files and images as they are accessed. If False, load everything up front.

property reader: Optional[fontTools.ufoLib.UFOReader]

Returns the underlying fontTools.ufoLib.UFOReader.

renameGlyph(name: str, newName: str, overwrite: bool = False)None[source]

Renames a Glyph object in the default layer.

Parameters
  • name – The old name.

  • newName – The new name.

  • overwrite – If False, raises exception if newName is already taken. If True, overwrites (read: deletes) the old Glyph object.

renameLayer(name: str, newName: str, overwrite: bool = False)None[source]

Renames a Layer.

Parameters
  • name – The old name.

  • newName – The new name.

  • overwrite – If False, raises exception if newName is already taken. If True, overwrites (read: deletes) the old Layer object.

save(path: Optional[Union[str, bytes, os.PathLike[str], os.PathLike[bytes], fs.base.FS]] = None, formatVersion: int = 3, structure: Optional[fontTools.ufoLib.UFOFileStructure] = None, overwrite: bool = False, validate: bool = True)None[source]

Saves the font to path.

Parameters
  • path – The target path. If it is None, the path from the last save (except when that was a fs.base.FS) or when the font was first opened will be used.

  • formatVersion – The version to save the UFO as. Only version 3 is supported currently.

  • structure (fontTools.ufoLib.UFOFileStructure) – How to store the UFO. Can be either None, “zip” or “package”. If None, it tries to use the same structure as the original UFO at the output path. If “zip”, the UFO will be saved as compressed archive. If “package”, it is saved as a regular folder or “package”.

  • overwrite – If False, raises OSError when the target path exists. If True, overwrites the target path.

  • validate – If True, will validate the data in Font before writing it out. If False, will write out whatever is serializable.

unlazify()None[source]

Load all glyphs, data files and images if the Font object loaded them lazily previously.

write(writer: fontTools.ufoLib.UFOWriter, saveAs: Optional[bool] = None)None[source]

Writes this Font to a fontTools.ufoLib.UFOWriter.

Parameters
  • writer – The fontTools.ufoLib.UFOWriter to write to.

  • saveAs – If True, tells the writer to save out-of-place. If False, tells the writer to save in-place. This affects how resources are cleaned before writing.

Info

class ufoLib2.objects.Info(familyName: Optional[str] = None, styleName: Optional[str] = None, styleMapFamilyName: Optional[str] = None, styleMapStyleName: Optional[str] = None, versionMajor: Optional[int] = None, versionMinor: Optional[int] = None, copyright: Optional[str] = None, trademark: Optional[str] = None, unitsPerEm: Optional[float] = None, descender: Optional[float] = None, xHeight: Optional[float] = None, capHeight: Optional[float] = None, ascender: Optional[float] = None, italicAngle: Optional[float] = None, note: Optional[str] = None, guidelines: Optional[Sequence[Union[ufoLib2.objects.guideline.Guideline, Any]]] = None, openTypeGaspRangeRecords: Optional[Sequence[Union[ufoLib2.objects.info.GaspRangeRecord, Any]]] = None, openTypeHeadCreated: Optional[str] = None, openTypeHeadLowestRecPPEM: Optional[int] = None, openTypeHeadFlags: Optional[List[int]] = None, openTypeHheaAscender: Optional[int] = None, openTypeHheaDescender: Optional[int] = None, openTypeHheaLineGap: Optional[int] = None, openTypeHheaCaretSlopeRise: Optional[int] = None, openTypeHheaCaretSlopeRun: Optional[int] = None, openTypeHheaCaretOffset: Optional[int] = None, openTypeNameDesigner: Optional[str] = None, openTypeNameDesignerURL: Optional[str] = None, openTypeNameManufacturer: Optional[str] = None, openTypeNameManufacturerURL: Optional[str] = None, openTypeNameLicense: Optional[str] = None, openTypeNameLicenseURL: Optional[str] = None, openTypeNameVersion: Optional[str] = None, openTypeNameUniqueID: Optional[str] = None, openTypeNameDescription: Optional[str] = None, openTypeNamePreferredFamilyName: Optional[str] = None, openTypeNamePreferredSubfamilyName: Optional[str] = None, openTypeNameCompatibleFullName: Optional[str] = None, openTypeNameSampleText: Optional[str] = None, openTypeNameWWSFamilyName: Optional[str] = None, openTypeNameWWSSubfamilyName: Optional[str] = None, openTypeNameRecords: Optional[Sequence[Union[ufoLib2.objects.info.NameRecord, Any]]] = None, openTypeOS2WidthClass: Optional[int] = None, openTypeOS2WeightClass: Optional[int] = None, openTypeOS2Selection: Optional[List[int]] = None, openTypeOS2VendorID: Optional[str] = None, openTypeOS2Panose: Optional[List[int]] = None, openTypeOS2FamilyClass: Optional[List[int]] = None, openTypeOS2UnicodeRanges: Optional[List[int]] = None, openTypeOS2CodePageRanges: Optional[List[int]] = None, openTypeOS2TypoAscender: Optional[int] = None, openTypeOS2TypoDescender: Optional[int] = None, openTypeOS2TypoLineGap: Optional[int] = None, openTypeOS2WinAscent: Optional[int] = None, openTypeOS2WinDescent: Optional[int] = None, openTypeOS2Type: Optional[List[int]] = None, openTypeOS2SubscriptXSize: Optional[int] = None, openTypeOS2SubscriptYSize: Optional[int] = None, openTypeOS2SubscriptXOffset: Optional[int] = None, openTypeOS2SubscriptYOffset: Optional[int] = None, openTypeOS2SuperscriptXSize: Optional[int] = None, openTypeOS2SuperscriptYSize: Optional[int] = None, openTypeOS2SuperscriptXOffset: Optional[int] = None, openTypeOS2SuperscriptYOffset: Optional[int] = None, openTypeOS2StrikeoutSize: Optional[int] = None, openTypeOS2StrikeoutPosition: Optional[int] = None, openTypeVheaVertTypoAscender: Optional[int] = None, openTypeVheaVertTypoDescender: Optional[int] = None, openTypeVheaVertTypoLineGap: Optional[int] = None, openTypeVheaCaretSlopeRise: Optional[int] = None, openTypeVheaCaretSlopeRun: Optional[int] = None, openTypeVheaCaretOffset: Optional[int] = None, postscriptFontName: Optional[str] = None, postscriptFullName: Optional[str] = None, postscriptSlantAngle: Optional[float] = None, postscriptUniqueID: Optional[int] = None, postscriptUnderlineThickness: Optional[float] = None, postscriptUnderlinePosition: Optional[float] = None, postscriptIsFixedPitch: Optional[bool] = None, postscriptBlueValues: Optional[List[float]] = None, postscriptOtherBlues: Optional[List[float]] = None, postscriptFamilyBlues: Optional[List[float]] = None, postscriptFamilyOtherBlues: Optional[List[float]] = None, postscriptStemSnapH: Optional[List[float]] = None, postscriptStemSnapV: Optional[List[float]] = None, postscriptBlueFuzz: Optional[float] = None, postscriptBlueShift: Optional[float] = None, postscriptBlueScale: Optional[float] = None, postscriptForceBold: Optional[bool] = None, postscriptDefaultWidthX: Optional[float] = None, postscriptNominalWidthX: Optional[float] = None, postscriptWeightName: Optional[str] = None, postscriptDefaultCharacter: Optional[str] = None, postscriptWindowsCharacterSet: Optional[str] = None, macintoshFONDName: Optional[str] = None, macintoshFONDFamilyID: Optional[int] = None, year: Optional[int] = None)[source]

A data class representing the contents of fontinfo.plist.

The attributes are formally specified at http://unifiedfontobject.org/versions/ufo3/fontinfo.plist/. Value validation is mostly done during saving and loading.

ascender
capHeight
copyright
descender
familyName
property guidelines: Optional[List[ufoLib2.objects.guideline.Guideline]]
italicAngle
macintoshFONDFamilyID
macintoshFONDName
note
property openTypeGaspRangeRecords: Optional[List[ufoLib2.objects.info.GaspRangeRecord]]
openTypeHeadCreated
openTypeHeadFlags
openTypeHeadLowestRecPPEM
openTypeHheaAscender
openTypeHheaCaretOffset
openTypeHheaCaretSlopeRise
openTypeHheaCaretSlopeRun
openTypeHheaDescender
openTypeHheaLineGap
openTypeNameCompatibleFullName
openTypeNameDescription
openTypeNameDesigner
openTypeNameDesignerURL
openTypeNameLicense
openTypeNameLicenseURL
openTypeNameManufacturer
openTypeNameManufacturerURL
openTypeNamePreferredFamilyName
openTypeNamePreferredSubfamilyName
property openTypeNameRecords: Optional[List[ufoLib2.objects.info.NameRecord]]
openTypeNameSampleText
openTypeNameUniqueID
openTypeNameVersion
openTypeNameWWSFamilyName
openTypeNameWWSSubfamilyName
openTypeOS2CodePageRanges
openTypeOS2FamilyClass
openTypeOS2Panose
openTypeOS2Selection
openTypeOS2StrikeoutPosition
openTypeOS2StrikeoutSize
openTypeOS2SubscriptXOffset
openTypeOS2SubscriptXSize
openTypeOS2SubscriptYOffset
openTypeOS2SubscriptYSize
openTypeOS2SuperscriptXOffset
openTypeOS2SuperscriptXSize
openTypeOS2SuperscriptYOffset
openTypeOS2SuperscriptYSize
openTypeOS2Type
openTypeOS2TypoAscender
openTypeOS2TypoDescender
openTypeOS2TypoLineGap
openTypeOS2UnicodeRanges
openTypeOS2VendorID
openTypeOS2WeightClass
property openTypeOS2WidthClass: Optional[ufoLib2.objects.info.WidthClass]
openTypeOS2WinAscent
openTypeOS2WinDescent
openTypeVheaCaretOffset
openTypeVheaCaretSlopeRise
openTypeVheaCaretSlopeRun
openTypeVheaVertTypoAscender
openTypeVheaVertTypoDescender
openTypeVheaVertTypoLineGap
postscriptBlueFuzz
postscriptBlueScale
postscriptBlueShift
postscriptBlueValues
postscriptDefaultCharacter
postscriptDefaultWidthX
postscriptFamilyBlues
postscriptFamilyOtherBlues
postscriptFontName
postscriptForceBold
postscriptFullName
postscriptIsFixedPitch
postscriptNominalWidthX
postscriptOtherBlues
postscriptSlantAngle
postscriptStemSnapH
postscriptStemSnapV
postscriptUnderlinePosition
postscriptUnderlineThickness
postscriptUniqueID
postscriptWeightName
postscriptWindowsCharacterSet
classmethod read(reader: fontTools.ufoLib.UFOReader)ufoLib2.objects.info.Info[source]

Instantiates a Info object from a fontTools.ufoLib.UFOReader.

styleMapFamilyName
styleMapStyleName
styleName
trademark
unitsPerEm
versionMajor
versionMinor
xHeight
year

Features

class ufoLib2.objects.features.Features(text: str = '')[source]

A data class representing UFO features.

See http://unifiedfontobject.org/versions/ufo3/features.fea/.

text

Holds the content of the features.fea file.

DataSet

class ufoLib2.objects.dataSet.DataSet(data: Dict[str, Union[bytes, ufoLib2.objects.misc.Placeholder]] = NOTHING)[source]

Represents a mapping of POSIX filename strings to arbitrary data bytes.

Always use forward slahes (/) as directory separators, even on Windows.

Behavior:

DataSet behaves like a dictionary of type Dict[str, bytes].

>>> from ufoLib2 import Font
>>> font = Font()
>>> font.data["test.txt"] = b"123"
>>> font.data["directory/my_binary_blob.bin"] = b"456"
>>> font.data["test.txt"]
b'123'
>>> del font.data["test.txt"]
>>> list(font.data.items())
[('directory/my_binary_blob.bin', b'456')]
clear()None.  Remove all items from D.
property fileNames: List[str]

Returns a list of filenames in the data store.

get(k[, d])D[k] if k in D, else d.  d defaults to None.
items()a set-like object providing a view on D’s items
keys()a set-like object providing a view on D’s keys
pop(k[, d])v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem()(k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

classmethod read(reader: fontTools.ufoLib.UFOReader, lazy: bool = True)Tds

Instantiate the data store from a fontTools.ufoLib.UFOReader.

setdefault(k[, d])D.get(k,d), also set D[k]=d if k not in D
unlazify()None

Load all data into memory.

update([E, ]**F)None.  Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values()an object providing a view on D’s values
write(writer: fontTools.ufoLib.UFOWriter, saveAs: Optional[bool] = None)None

Write the data store to a fontTools.ufoLib.UFOWriter.

LayerSet

class ufoLib2.objects.LayerSet(layers: OrderedDict[str, Union[Layer, Placeholder]], defaultLayer: ufoLib2.objects.layer.Layer)[source]

Represents a mapping of layer names to Layer objects.

See http://unifiedfontobject.org/versions/ufo3/layercontents.plist/ for layer semantics.

Behavior:

LayerSet behaves partly like a dictionary of type Dict[str, Layer], but creating and loading layers is done through their own methods. Unless the font is loaded eagerly (with lazy=False), the layer objects and their glyphs are by default only loaded into memory when accessed.

To get the number of layers in the font:

layerCount = len(font.layers)

To iterate over all layers:

for layer in font.layers:
    ...

To check if a specific layer exists:

exists = "myLayerName" in font.layers

To get a specific layer:

font.layers["myLayerName"]

To delete a specific layer:

del font.layers["myLayerName"]
classmethod default()ufoLib2.objects.layerSet.LayerSet[source]

Return a new LayerSet with an empty default Layer.

defaultLayer

The Layer that is marked as the default, typically named public.default.

classmethod from_iterable(value: Iterable[ufoLib2.objects.layer.Layer], defaultLayerName: str = 'public.default')ufoLib2.objects.layerSet.LayerSet[source]

Instantiates a LayerSet from an iterable of Layer objects.

Parameters
  • value – an iterable of Layer objects.

  • defaultLayerName – the name of the default layer of the ones in value.

get(name: str, default: Optional[T] = None)Union[T, None, ufoLib2.objects.layer.Layer][source]
keys()AbstractSet[str][source]
property layerOrder: List[str]

The font’s layer order.

Getter:

Returns the font’s layer order.

Note

The getter always returns a new list, modifications to it do not change the LayerSet.

Setter:

Sets the font’s layer order. The set order value must contain all layers that are present in the LayerSet.

newLayer(name: str, **kwargs: Any)ufoLib2.objects.layer.Layer[source]

Creates and returns a named layer.

Parameters
  • name – The layer name.

  • kwargs – Arguments passed to the constructor of Layer.

classmethod read(reader: fontTools.ufoLib.UFOReader, lazy: bool = True)ufoLib2.objects.layerSet.LayerSet[source]

Instantiates a LayerSet object from a fontTools.ufoLib.UFOReader.

Parameters
  • path – The path to the UFO to load.

  • lazy – If True, load glyphs, data files and images as they are accessed. If False, load everything up front.

renameGlyph(name: str, newName: str, overwrite: bool = False)None[source]

Renames a glyph across all layers.

Parameters
  • name – The old name.

  • newName – The new name.

  • overwrite – If False, raises exception if newName is already taken in any layer. If True, overwrites (read: deletes) the old Glyph object.

renameLayer(name: str, newName: str, overwrite: bool = False)None[source]

Renames a layer.

Parameters
  • name – The old name.

  • newName – The new name.

  • overwrite – If False, raises exception if newName is already taken. If True, overwrites (read: deletes) the old Layer object.

unlazify()None[source]

Load all layers into memory.

write(writer: fontTools.ufoLib.UFOWriter, saveAs: Optional[bool] = None)None[source]

Writes this LayerSet to a fontTools.ufoLib.UFOWriter.

Parameters
  • writer (fontTools.ufoLib.UFOWriter) – The writer to write to.

  • saveAs – If True, tells the writer to save out-of-place. If False, tells the writer to save in-place. This affects how resources are cleaned before writing.

Layer

class ufoLib2.objects.Layer(name: str = 'public.default', glyphs: Union[Dict[str, Union[ufoLib2.objects.glyph.Glyph, ufoLib2.objects.misc.Placeholder]], Sequence[ufoLib2.objects.glyph.Glyph]] = NOTHING, color: Optional[str] = None, lib: Dict[str, Any] = NOTHING)[source]

Represents a Layer that holds Glyph objects.

See http://unifiedfontobject.org/versions/ufo3/glyphs/layerinfo.plist/.

Note

Various methods that work on Glyph objects take a layer attribute, because the UFO data model prescribes that Components within a Glyph object refer to glyphs within the same layer.

Behavior:

Layer behaves partly like a dictionary of type Dict[str, Glyph]. Unless the font is loaded eagerly (with lazy=False), the Glyph objects by default are only loaded into memory when accessed.

To get the number of glyphs in the layer:

glyphCount = len(layer)

To iterate over all glyphs:

for glyph in layer:
    ...

To check if a specific glyph exists:

exists = "myGlyphName" in layer

To get a specific glyph:

layer["myGlyphName"]

To delete a specific glyph:

del layer["myGlyphName"]
addGlyph(glyph: ufoLib2.objects.glyph.Glyph)None[source]

Appends glyph object to the this layer unless its name is already taken.

property bounds: Optional[ufoLib2.objects.misc.BoundingBox]

Returns the (xMin, yMin, xMax, yMax) bounding box of the layer, taking the actual contours into account.

For defcon API compatibility only.

color

The color assigned to the layer.

property controlPointBounds: Optional[ufoLib2.objects.misc.BoundingBox]

Returns the (xMin, yMin, xMax, yMax) bounding box of the layer, taking only the control points into account.

For defcon API compatibility only.

get(name: str, default: Optional[T] = None)Union[T, None, ufoLib2.objects.glyph.Glyph][source]

Return the Glyph object for name if it is present in this layer, otherwise return default.

insertGlyph(glyph: ufoLib2.objects.glyph.Glyph, name: Optional[str] = None, overwrite: bool = True, copy: bool = True)None[source]

Inserts Glyph object into this layer.

Parameters
  • glyph – The Glyph object.

  • name – The name of the glyph.

  • overwrite – If True, overwrites (read: deletes) glyph with the same name if it exists. If False, raises KeyError.

  • copy – If True, copies the Glyph object before insertion. If False, inserts as is.

instantiateGlyphObject()ufoLib2.objects.glyph.Glyph[source]

Returns a new Glyph instance.

For defcon API compatibility only.

keys()KeysView[str][source]

Returns a list of glyph names.

lib

The layer’s lib for mapping string keys to arbitrary data.

loadGlyph(name: str)ufoLib2.objects.glyph.Glyph[source]

Load and return Glyph object.

property name: str

The name of the layer.

newGlyph(name: str)ufoLib2.objects.glyph.Glyph[source]

Creates and returns new Glyph object in this layer with name.

pop(key: str)ufoLib2.objects.glyph.Glyph[source]
pop(key: str, default: Union[ufoLib2.objects.glyph.Glyph, T] = <class 'KeyError'>)Union[ufoLib2.objects.glyph.Glyph, T]

Remove and return glyph from layer.

Parameters
  • key – The name of the glyph.

  • default – What to return if there is no glyph with the given name.

classmethod read(name: str, glyphSet: fontTools.ufoLib.glifLib.GlyphSet, lazy: bool = True)ufoLib2.objects.layer.Layer[source]

Instantiates a Layer object from a fontTools.ufoLib.glifLib.GlyphSet.

Parameters
  • name – The name of the layer.

  • glyphSet – The GlyphSet object to read from.

  • lazy – If True, load glyphs as they are accessed. If False, load everything up front.

renameGlyph(name: str, newName: str, overwrite: bool = False)None[source]

Renames a Glyph object in this layer.

Parameters
  • name – The old name.

  • newName – The new name.

  • overwrite – If False, raises exception if newName is already taken. If True, overwrites (read: deletes) the old Glyph object.

unlazify()None[source]

Load all glyphs into memory.

write(glyphSet: fontTools.ufoLib.glifLib.GlyphSet, saveAs: bool = True)None[source]

Write Layer to a fontTools.ufoLib.glifLib.GlyphSet.

Parameters
  • glyphSet – The GlyphSet object to write to.

  • saveAs – If True, tells the writer to save out-of-place. If False, tells the writer to save in-place. This affects how resources are cleaned before writing.

Glyph

class ufoLib2.objects.Glyph(name: Optional[str] = None, width: float = 0, height: float = 0, unicodes: List[int] = NOTHING, image: ufoLib2.objects.image.Image = NOTHING, lib: Dict[str, Any] = NOTHING, note: Optional[str] = None, anchors: List[ufoLib2.objects.anchor.Anchor] = NOTHING, components: List[ufoLib2.objects.component.Component] = NOTHING, contours: List[ufoLib2.objects.contour.Contour] = NOTHING, guidelines: List[ufoLib2.objects.guideline.Guideline] = NOTHING)[source]

Represents a glyph, containing contours, components, anchors and various other bits of data concerning it.

See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/.

Behavior:

The Glyph object has list-like behavior. This behavior allows you to interact with contour data directly. For example, to get a particular contour:

contour = glyph[0]

To iterate over all contours:

for contour in glyph:
    ...

To get the number of contours:

contourCount = len(glyph)

To check if a Contour object is in glyph:

exists = contour in glyph

To interact with components or anchors in a similar way, use the Glyph.components and Glyph.anchors attributes.

property anchors: List[ufoLib2.objects.anchor.Anchor]

The list of anchors the glyph contains.

Getter:

Returns a list of anchors the glyph contains. Modifications of the list modify the Glyph object.

Setter:

Clears current anchors and sets the new ones.

appendAnchor(anchor: Union[ufoLib2.objects.anchor.Anchor, Mapping[str, Any]])None[source]

Appends an Anchor object to glyph’s list of anchors.

Parameters

anchor – An Anchor object or mapping for the Anchor constructor.

appendContour(contour: ufoLib2.objects.contour.Contour)None[source]

Appends a Contour object to glyph’s list of contours.

appendGuideline(guideline: Union[ufoLib2.objects.guideline.Guideline, Mapping[str, Any]])None[source]

Appends a Guideline object to glyph’s list of guidelines.

Parameters

guideline – A Guideline object or a mapping for the Guideline constructor.

clear()None[source]

Clears out anchors, components, contours, guidelines and image references.

clearAnchors()None[source]

Clears out anchors.

clearComponents()None[source]

Clears out components.

clearContours()None[source]

Clears out contours.

clearGuidelines()None[source]

Clears out guidelines.

components

The list of components the glyph contains.

contours

The list of contours the glyph contains.

copy(name: Optional[str] = None)ufoLib2.objects.glyph.Glyph[source]

Returns a new Glyph (deep) copy, optionally override the new glyph name.

copyDataFromGlyph(glyph: ufoLib2.objects.glyph.Glyph)None[source]

Deep-copies everything from the other glyph into self, except for the name.

Existing glyph data is overwritten.

For defcon API compatibility only.

draw(pen: fontTools.pens.basePen.AbstractPen)None[source]

Draws glyph into given pen.

drawPoints(pointPen: fontTools.pens.pointPen.AbstractPointPen)None[source]

Draws points of glyph into given point pen.

getBottomMargin(layer: Optional[ufoLib2.typing.GlyphSet] = None)Optional[float][source]

Returns the the space in font units from the bottom of the canvas to the bottom of the glyph.

Parameters

layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.

getBounds(layer: Optional[ufoLib2.typing.GlyphSet] = None)Optional[ufoLib2.objects.misc.BoundingBox][source]

Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking the actual contours into account.

Parameters

layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.

getControlBounds(layer: Optional[ufoLib2.typing.GlyphSet] = None)Optional[ufoLib2.objects.misc.BoundingBox][source]

Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking only the control points into account.

Parameters

layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.

getLeftMargin(layer: Optional[ufoLib2.typing.GlyphSet] = None)Optional[float][source]

Returns the the space in font units from the point of origin to the left side of the glyph.

Parameters

layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.

getPen()fontTools.pens.basePen.AbstractPen[source]

Returns a pen for others to draw into self.

getPointPen()fontTools.pens.pointPen.AbstractPointPen[source]

Returns a point pen for others to draw points into self.

getRightMargin(layer: Optional[ufoLib2.typing.GlyphSet] = None)Optional[float][source]

Returns the the space in font units from the glyph’s advance width to the right side of the glyph.

Parameters

layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.

getTopMargin(layer: Optional[ufoLib2.typing.GlyphSet] = None)Optional[float][source]

Returns the the space in font units from the top of the canvas to the top of the glyph.

Parameters

layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.

property guidelines: List[ufoLib2.objects.guideline.Guideline]

The list of guidelines the glyph contains.

Getter:

Returns a list of guidelines the glyph contains. Modifications of the list modify the Glyph object.

Setter:

Clears current guidelines and sets the new ones.

height

The height of the glyph.

property image: ufoLib2.objects.image.Image

The background image reference associated with the glyph.

See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#image.

Setter:

Sets the background image reference. Clears it if value is None.

lib

The glyph’s mapping of string keys to arbitrary data.

property markColor: Optional[str]

The color assigned to the glyph.

See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#publicmarkcolor.

Getter:

Returns the mark color or None.

Setter:

Sets the mark color. If value is None, deletes the key from the lib if present.

move(delta: Tuple[float, float])None[source]

Moves all contours, components and anchors by (x, y) font units.

property name: Optional[str]

The name of the glyph.

note

A free form text note about the glyph.

objectLib(object: ufoLib2.typing.HasIdentifier)Dict[str, Any][source]

Return the lib for an object with an identifier, as stored in a glyph’s lib.

If the object does not yet have an identifier, a new one is assigned to it. If the font lib does not yet contain the object’s lib, a new one is inserted and returned.

>>> from ufoLib2.objects import Font, Guideline
>>> font = Font()
>>> glyph = font.newGlyph("a")
>>> glyph.guidelines = [Guideline(x=100)]
>>> guideline_lib = glyph.objectLib(glyph.guidelines[0])
>>> guideline_lib["com.test.foo"] = 1234
>>> guideline_id = glyph.guidelines[0].identifier
>>> assert guideline_id is not None
>>> assert glyph.lib["public.objectLibs"][guideline_id] is guideline_lib
removeComponent(component: ufoLib2.objects.component.Component)None[source]

Removes Component object from the glyph’s list of components.

setBottomMargin(value: float, layer: Optional[ufoLib2.typing.GlyphSet] = None)None[source]

Sets the the space in font units from the bottom of the canvas to the bottom of the glyph.

Parameters
  • value – The desired bottom margin in font units.

  • layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.

setLeftMargin(value: float, layer: Optional[ufoLib2.typing.GlyphSet] = None)None[source]

Sets the the space in font units from the point of origin to the left side of the glyph.

Parameters
  • value – The desired left margin in font units.

  • layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.

setRightMargin(value: float, layer: Optional[ufoLib2.typing.GlyphSet] = None)None[source]

Sets the the space in font units from the glyph’s advance width to the right side of the glyph.

Parameters
  • value – The desired right margin in font units.

  • layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.

setTopMargin(value: float, layer: Optional[ufoLib2.typing.GlyphSet] = None)None[source]

Sets the the space in font units from the top of the canvas to the top of the glyph.

Parameters
  • value – The desired top margin in font units.

  • layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.

property unicode: Optional[int]

The first assigned Unicode code point or None.

See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#unicode.

Setter:

Sets the value to be the first of the assigned Unicode code points. Will remove a duplicate if exists. Will clear the list of Unicode points if value is None.

unicodes

The Unicode code points assigned to the glyph. Note that a glyph can have multiple.

property verticalOrigin: Optional[float]

The vertical origin of the glyph.

See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#publicverticalorigin.

Getter:

Returns the vertical origin or None.

Setter:

Sets the vertical origin. If value is None, deletes the key from the lib if present.

width

The width of the glyph.

Component

class ufoLib2.objects.Component(baseGlyph: str, transformation: Union[fontTools.misc.transform.Transform, Sequence[float]] = <Transform [1 0 0 1 0 0]>, identifier: Optional[str] = None)[source]

Represents a reference to another glyph in the same layer.

See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#component.

Note

Components always refer to glyphs in the same layer. Referencing different layers is currently not possible in the UFO data model.

baseGlyph

The name of the glyph in the same layer to insert.

draw(pen: fontTools.pens.basePen.AbstractPen)None[source]

Draws component with given pen.

drawPoints(pointPen: fontTools.pens.pointPen.AbstractPointPen)None[source]

Draws points of component with given point pen.

getBounds(layer: ufoLib2.typing.GlyphSet)Optional[ufoLib2.objects.misc.BoundingBox][source]

Returns the (xMin, yMin, xMax, yMax) bounding box of the component, taking the actual contours into account.

Parameters

layer – The layer of the containing glyph to look up components.

getControlBounds(layer: ufoLib2.typing.GlyphSet)Optional[ufoLib2.objects.misc.BoundingBox][source]

Returns the (xMin, yMin, xMax, yMax) bounding box of the component, taking only the control points into account.

Parameters

layer – The layer of the containing glyph to look up components.

identifier

The globally unique identifier of the component.

move(delta: Tuple[float, float])None[source]

Moves this component by (x, y) font units.

NOTE: This interprets the delta to be the visual delta, as in, it replaces the x and y offsets of the component’s transformation directly, rather than going through fontTools.misc.transform.Transform.translate(). Otherwise, composites that use flipped components (imagine a quotedblleft composite using two x- and y-inverted comma components) would move in the opposite direction of the delta.

transformation

The affine transformation to apply to the Component.baseGlyph.

Contour

class ufoLib2.objects.Contour(points: List[ufoLib2.objects.point.Point] = NOTHING, identifier: Optional[str] = None)[source]

Represents a contour as a list of points.

Behavior:

The Contour object has list-like behavior. This behavior allows you to interact with point data directly. For example, to get a particular point:

point = contour[0]

To iterate over all points:

for point in contour:
    ...

To get the number of points:

pointCount = len(contour)

To delete a particular point:

del contour[0]

To set a particular point to another Point object:

contour[0] = anotherPoint
property bounds: Optional[ufoLib2.objects.misc.BoundingBox]

Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking the actual contours into account.

For defcon API compatibility only.

property controlPointBounds: Optional[ufoLib2.objects.misc.BoundingBox]

Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking only the control points into account.

For defcon API compatibility only.

draw(pen: fontTools.pens.basePen.AbstractPen)None[source]

Draws contour into given pen.

drawPoints(pointPen: fontTools.pens.pointPen.AbstractPointPen)None[source]

Draws points of contour into given point pen.

getBounds(layer: Optional[ufoLib2.typing.GlyphSet] = None)Optional[ufoLib2.objects.misc.BoundingBox][source]

Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking the actual contours into account.

Parameters

layer – Not applicable to contours, here for API symmetry.

getControlBounds(layer: Optional[ufoLib2.typing.GlyphSet] = None)Optional[ufoLib2.objects.misc.BoundingBox][source]

Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking only the control points into account.

Parameters

layer – Not applicable to contours, here for API symmetry.

identifier

The globally unique identifier of the contour.

insert(index: int, value: ufoLib2.objects.point.Point)None[source]

Insert Point object value into the contour at index.

move(delta: Tuple[float, float])None[source]

Moves contour by (x, y) font units.

property open: bool

Returns whether the contour is open or closed.

points

The list of points in the contour.

Point

class ufoLib2.objects.Point(x: float, y: float, type: Optional[str] = None, smooth: bool = False, name: Optional[str] = None, identifier: Optional[str] = None)[source]

Represents a single point.

See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#point.

identifier

The globally unique identifier of the point.

move(delta: Tuple[float, float])None[source]

Moves point by (x, y) font units.

name

The name of the point, no uniqueness required.

property segmentType: Optional[str]

Returns the type of the point.

For defcon API compatibility only.

smooth

Whether a smooth curvature should be maintained at this point.

type

The type of the point.

None means “offcurve”.

See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#point-types.

x

The x coordinate of the point.

y

The y coordinate of the point.

Anchor

class ufoLib2.objects.Anchor(x: float, y: float, name: Optional[str] = None, color: Optional[str] = None, identifier: Optional[str] = None)[source]

Represents a single anchor.

See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#anchor.

color

The color of the anchor.

identifier

The globally unique identifier of the anchor.

move(delta: Tuple[float, float])None[source]

Moves anchor by (x, y) font units.

name

The name of the anchor.

x

The x coordinate of the anchor.

y

The y coordinate of the anchor.

Guideline

class ufoLib2.objects.Guideline(x: Optional[float] = None, y: Optional[float] = None, angle: Optional[float] = None, name: Optional[str] = None, color: Optional[str] = None, identifier: Optional[str] = None)[source]

Represents a single guideline.

See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#guideline. Has some data composition restrictions.

angle

The angle of the guideline.

color

The color of the guideline.

identifier

The globally unique identifier of the guideline.

name

The name of the guideline, no uniqueness required.

x

The origin x coordinate of the guideline.

y

The origin y coordinate of the guideline.

ImageSet

class ufoLib2.objects.imageSet.ImageSet(data: Dict[str, Union[bytes, ufoLib2.objects.misc.Placeholder]] = NOTHING)[source]

Represents a mapping of POSIX filename strings to arbitrary image data.

Note

Images cannot be put into subdirectories of the images folder.

Behavior:

ImageSet behaves like a dictionary of type Dict[str, bytes].

>>> from ufoLib2 import Font
>>> font = Font()
>>> # Note: invalid PNG data for demonstration. Use the actual PNG bytes.
>>> font.images["test.png"] = b"123"
>>> font.images["test2.png"] = b"456"
>>> font.images["test.png"]
b'123'
>>> del font.images["test.png"]
>>> list(font.images.items())
[('test2.png', b'456')]
clear()None.  Remove all items from D.
property fileNames: List[str]

Returns a list of filenames in the data store.

get(k[, d])D[k] if k in D, else d.  d defaults to None.
items()a set-like object providing a view on D’s items
keys()a set-like object providing a view on D’s keys
pop(k[, d])v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem()(k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

classmethod read(reader: fontTools.ufoLib.UFOReader, lazy: bool = True)Tds

Instantiate the data store from a fontTools.ufoLib.UFOReader.

setdefault(k[, d])D.get(k,d), also set D[k]=d if k not in D
unlazify()None

Load all data into memory.

update([E, ]**F)None.  Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values()an object providing a view on D’s values
write(writer: fontTools.ufoLib.UFOWriter, saveAs: Optional[bool] = None)None

Write the data store to a fontTools.ufoLib.UFOWriter.

Image

class ufoLib2.objects.Image(fileName: Optional[str] = None, transformation: Union[fontTools.misc.transform.Transform, Sequence[float]] = <Transform [1 0 0 1 0 0]>, color: Optional[str] = None, transformation_keys_: Tuple[str, str, str, str, str, str] = ('xScale', 'xyScale', 'yxScale', 'yScale', 'xOffset', 'yOffset'), valid_keys_: Tuple[str, str, str, str, str, str, str, str] = ('fileName', 'xScale', 'xyScale', 'yxScale', 'yScale', 'xOffset', 'yOffset', 'color'))[source]

Represents a background image reference.

See http://unifiedfontobject.org/versions/ufo3/images/ and http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#image.

clear()None[source]

Resets the image reference to factory settings.

color

The color applied to the image.

fileName

The filename of the image.

transformation

The affine transformation applied to the image.

Miscellaneous objects

class ufoLib2.objects.misc.BoundingBox(xMin: float, yMin: float, xMax: float, yMax: float)[source]

Represents a bounding box as a tuple of (xMin, yMin, xMax, yMax).

property xMax

Alias for field number 2

property xMin

Alias for field number 0

property yMax

Alias for field number 3

property yMin

Alias for field number 1

Types

class ufoLib2.typing.Drawable(*args, **kwds)[source]

Stand-in for an object that can draw itself with a given pen.

See fontTools.pens.basePen for an introduction to pens.

draw(pen: fontTools.pens.basePen.AbstractPen)None[source]
class ufoLib2.typing.DrawablePoints(*args, **kwds)[source]

Stand-in for an object that can draw its points with a given pen.

See fontTools.pens.pointPen for an introduction to point pens.

drawPoints(pen: fontTools.pens.pointPen.AbstractPointPen)None[source]
class ufoLib2.typing.GlyphSet(*args, **kwds)[source]

Any container that holds drawable objects.

In ufoLib2, this usually refers to Font (referencing glyphs in the default layer) and Layer (referencing glyphs in that particular layer). Ideally, this would be a simple subclass of Mapping[str, Union[Drawable, DrawablePoints]], but due to historic reasons, the established objects don’t conform to Mapping exactly.

The protocol contains what is used in fontTools.pens at v4.18.2 (grep for .glyphSet).

class ufoLib2.typing.HasIdentifier(*args, **kwds)[source]

Any object that has a unique identifier in some context that can be used as a key in a public.objectLibs dictionary.

identifier: Optional[str]
ufoLib2.typing.PathLike = typing.Union[str, bytes, _ForwardRef('os.PathLike[str]'), _ForwardRef('os.PathLike[bytes]')]

Represents a path in various possible forms.

ufoLib2.typing.T

Generic variable for mypy for trivial generic function signatures.

alias of TypeVar(‘T’)

Pens

class ufoLib2.pointPens.glyphPointPen.GlyphPointPen(glyph: Glyph)[source]

A point pen.

See fontTools.pens.basePen and fontTools.pens.pointPen for an introduction to pens.

addComponent(baseGlyph: str, transformation: fontTools.misc.transform.Transform, identifier: Optional[str] = None, **kwargs: Any)None[source]

Add a sub glyph.

addPoint(pt: Tuple[float, float], segmentType: Optional[str] = None, smooth: bool = False, name: Optional[str] = None, identifier: Optional[str] = None, **kwargs: Any)None[source]

Add a point to the current sub path.

beginPath(identifier: Optional[str] = None, **kwargs: Any)None[source]

Start a new sub path.

endPath()None[source]

End the current sub path.

Constants

ufoLib2.constants.DEFAULT_LAYER_NAME: str = 'public.default'

The name of the default layer.

ufoLib2.constants.OBJECT_LIBS_KEY: str = 'public.objectLibs'

The lib key for object libs.

See:

Exceptions

exception ufoLib2.errors.Error[source]

The base exception for ufoLib2.