1 DesignSpaceDocument Python API

An object to read, write and edit interpolation systems for typefaces. Define sources, axes, rules, variable fonts and instances.

Get an overview of the available classes in the Class Diagram below:

UML class diagram of designspaceLib

UML class diagram of designspaceLib. Click to enlarge.

DesignSpaceDocument

class fontTools.designspaceLib.DesignSpaceDocument(readerClass=None, writerClass=None)[source]

The DesignSpaceDocument object can read and write .designspace data. It imports the axes, sources, variable fonts and instances to very basic descriptor objects that store the data in attributes. Data is added to the document by creating such descriptor objects, filling them with data and then adding them to the document. This makes it easy to integrate this object in different contexts.

The DesignSpaceDocument object can be subclassed to work with different objects, as long as they have the same attributes. Reader and Writer objects can be subclassed as well.

Note: Python attribute names are usually camelCased, the corresponding XML attributes are usually all lowercase.

from fontTools.designspaceLib import DesignSpaceDocument
doc = DesignSpaceDocument.fromfile("some/path/to/my.designspace")
doc.formatVersion
doc.elidedFallbackName
doc.axes
doc.locationLabels
doc.rules
doc.rulesProcessingLast
doc.sources
doc.variableFonts
doc.instances
doc.lib
asdict()
property log
path

String, optional. When the document is read from the disk, this is the full path that was given to read() or fromfile().

filename

String, optional. When the document is read from the disk, this is its original file name, i.e. the last part of its path.

When the document is produced by a Python script and still only exists in memory, the producing script can write here an indication of a possible “good” filename, in case one wants to save the file somewhere.

formatVersion: Optional[str]

Format version for this document, as a string. E.g. “4.0”

elidedFallbackName: Optional[str]

STAT Style Attributes Header field elidedFallbackNameID.

See: OTSpec STAT Style Attributes Header

New in version 5.0.

axes: List[Union[AxisDescriptor, DiscreteAxisDescriptor]]

List of this document’s axes.

locationLabels: List[LocationLabelDescriptor]

List of this document’s STAT format 4 labels.

New in version 5.0.

rules: List[RuleDescriptor]

List of this document’s rules.

rulesProcessingLast: bool

This flag indicates whether the substitution rules should be applied before or after other glyph substitution features.

  • False: before

  • True: after.

Default is False. For new projects, you probably want True. See the following issues for more information: fontTools#1371 fontTools#2050

If you want to use a different feature altogether, e.g. calt, use the lib key com.github.fonttools.varLib.featureVarsFeatureTag

<lib>
    <dict>
        <key>com.github.fonttools.varLib.featureVarsFeatureTag</key>
        <string>calt</string>
    </dict>
</lib>
sources: List[SourceDescriptor]

List of this document’s sources.

variableFonts: List[VariableFontDescriptor]

List of this document’s variable fonts.

New in version 5.0.

instances: List[InstanceDescriptor]

List of this document’s instances.

lib: Dict

User defined, custom data associated with the whole document.

Use reverse-DNS notation to identify your own data. Respect the data stored by others.

default: Optional[str]

Name of the default master.

This attribute is updated by the findDefault()

classmethod fromfile(path, readerClass=None, writerClass=None)[source]

Read a designspace file from path and return a new instance of :class:.

classmethod fromstring(string, readerClass=None, writerClass=None)[source]
tostring(encoding=None)[source]

Returns the designspace as a string. Default encoding utf-8.

read(path)[source]

Read a designspace file from path and populates the fields of self with the data.

write(path)[source]

Write this designspace to path.

updatePaths()[source]

Right before we save we need to identify and respond to the following situations: In each descriptor, we have to do the right thing for the filename attribute.

case 1.
descriptor.filename == None
descriptor.path == None

-- action:
write as is, descriptors will not have a filename attr.
useless, but no reason to interfere.


case 2.
descriptor.filename == "../something"
descriptor.path == None

-- action:
write as is. The filename attr should not be touched.


case 3.
descriptor.filename == None
descriptor.path == "~/absolute/path/there"

-- action:
calculate the relative path for filename.
We're not overwriting some other value for filename, it should be fine


case 4.
descriptor.filename == '../somewhere'
descriptor.path == "~/absolute/path/there"

-- action:
there is a conflict between the given filename, and the path.
So we know where the file is relative to the document.
Can't guess why they're different, we just choose for path to be correct and update filename.
addSource(sourceDescriptor: SourceDescriptor)[source]

Add the given sourceDescriptor to doc.sources.

addSourceDescriptor(**kwargs)[source]

Instantiate a new SourceDescriptor using the given kwargs and add it to doc.sources.

addInstance(instanceDescriptor: InstanceDescriptor)[source]

Add the given instanceDescriptor to instances.

addInstanceDescriptor(**kwargs)[source]

Instantiate a new InstanceDescriptor using the given kwargs and add it to instances.

addAxis(axisDescriptor: Union[AxisDescriptor, DiscreteAxisDescriptor])[source]

Add the given axisDescriptor to axes.

addAxisDescriptor(**kwargs)[source]

Instantiate a new AxisDescriptor using the given kwargs and add it to axes.

The axis will be and instance of DiscreteAxisDescriptor if the kwargs provide a value, or a AxisDescriptor otherwise.

addRule(ruleDescriptor: RuleDescriptor)[source]

Add the given ruleDescriptor to rules.

addRuleDescriptor(**kwargs)[source]

Instantiate a new RuleDescriptor using the given kwargs and add it to rules.

addVariableFont(variableFontDescriptor: VariableFontDescriptor)[source]

Add the given variableFontDescriptor to variableFonts.

New in version 5.0.

addVariableFontDescriptor(**kwargs)[source]

Instantiate a new VariableFontDescriptor using the given kwargs and add it to variableFonts.

New in version 5.0.

addLocationLabel(locationLabelDescriptor: LocationLabelDescriptor)[source]

Add the given locationLabelDescriptor to locationLabels.

New in version 5.0.

addLocationLabelDescriptor(**kwargs)[source]

Instantiate a new LocationLabelDescriptor using the given kwargs and add it to locationLabels.

New in version 5.0.

newDefaultLocation()[source]

Return a dict with the default location in design space coordinates.

labelForUserLocation(userLocation: Dict[str, float]) Optional[LocationLabelDescriptor][source]

Return the LocationLabel that matches the given userLocation, or None if no such label exists.

New in version 5.0.

updateFilenameFromPath(masters=True, instances=True, force=False)[source]

Set a descriptor filename attr from the path and this document path.

If the filename attribute is not None: skip it.

newAxisDescriptor()[source]

Ask the writer class to make us a new axisDescriptor.

newSourceDescriptor()[source]

Ask the writer class to make us a new sourceDescriptor.

newInstanceDescriptor()[source]

Ask the writer class to make us a new instanceDescriptor.

getAxisOrder()[source]

Return a list of axis names, in the same order as defined in the document.

getAxis(name)[source]

Return the axis with the given name, or None if no such axis exists.

getLocationLabel(name: str) Optional[LocationLabelDescriptor][source]

Return the top-level location label with the given name, or None if no such label exists.

New in version 5.0.

map_forward(userLocation: Dict[str, float]) Dict[str, float][source]

Map a user location to a design location.

Assume that missing coordinates are at the default location for that axis.

Note: the output won’t be anisotropic, only the xvalue is set.

New in version 5.0.

map_backward(designLocation: Dict[str, Union[float, Tuple[float, float]]]) Dict[str, float][source]

Map a design location to a user location.

Assume that missing coordinates are at the default location for that axis.

When the input has anisotropic locations, only the xvalue is used.

New in version 5.0.

findDefault()[source]

Set and return SourceDescriptor at the default location or None.

The default location is the set of all default values in user space of all axes.

This function updates the document’s default value.

Changed in version 5.0: Allow the default source to not specify some of the axis values, and they are assumed to be the default. See SourceDescriptor.getFullDesignLocation()

normalizeLocation(location)[source]

Return a dict with normalized axis values.

normalize()[source]

Normalise the geometry of this designspace:

  • scale all the locations of all masters and instances to the -1 - 0 - 1 value.

  • we need the axis data to do the scaling, so we do those last.

loadSourceFonts(opener, **kwargs)[source]

Ensure SourceDescriptor.font attributes are loaded, and return list of fonts.

Takes a callable which initializes a new font object (e.g. TTFont, or defcon.Font, etc.) from the SourceDescriptor.path, and sets the SourceDescriptor.font attribute. If the font attribute is already not None, it is not loaded again. Fonts with the same path are only loaded once and shared among SourceDescriptors.

For example, to load UFO sources using defcon:

designspace = DesignSpaceDocument.fromfile(“path/to/my.designspace”) designspace.loadSourceFonts(defcon.Font)

Or to load masters as FontTools binary fonts, including extra options:

designspace.loadSourceFonts(ttLib.TTFont, recalcBBoxes=False)

Parameters
  • opener (Callable) – takes one required positional argument, the source.path, and an optional list of keyword arguments, and returns a new font object loaded from the path.

  • **kwargs – extra options passed on to the opener function.

Returns

List of font objects in the order they appear in the sources list.

property formatTuple

Return the formatVersion as a tuple of (major, minor).

New in version 5.0.

getVariableFonts() List[VariableFontDescriptor][source]

Return all variable fonts defined in this document, or implicit variable fonts that can be built from the document’s continuous axes.

In the case of Designspace documents before version 5, the whole document was implicitly describing a variable font that covers the whole space.

In version 5 and above documents, there can be as many variable fonts as there are locations on discrete axes.

See also

splitInterpolable()

New in version 5.0.

deepcopyExceptFonts()[source]

Allow deep-copying a DesignSpace document without deep-copying attached UFO fonts or TTFont objects. The font attribute is shared by reference between the original and the copy.

New in version 5.0.

AxisDescriptor

class fontTools.designspaceLib.AxisDescriptor(*, tag=None, name=None, labelNames=None, minimum=None, default=None, maximum=None, hidden=False, map=None, axisOrdering=None, axisLabels=None)[source]

Simple container for the axis data.

Add more localisations?

a1 = AxisDescriptor()
a1.minimum = 1
a1.maximum = 1000
a1.default = 400
a1.name = "weight"
a1.tag = "wght"
a1.labelNames['fa-IR'] = "قطر"
a1.labelNames['en'] = "Wéíght"
a1.map = [(1.0, 10.0), (400.0, 66.0), (1000.0, 990.0)]
a1.axisOrdering = 1
a1.axisLabels = [
    AxisLabelDescriptor(name="Regular", userValue=400, elidable=True)
]
doc.addAxis(a1)
minimum

number. The minimum value for this axis in user space.

MutatorMath + Varlib.

maximum

number. The maximum value for this axis in user space.

MutatorMath + Varlib.

default

number. The default value for this axis, i.e. when a new location is created, this is the value this axis will get in user space.

MutatorMath + Varlib.

serialize()[source]
map_forward(v)[source]

Maps value from axis mapping’s input (user) to output (design).

map_backward(v)[source]

Maps value from axis mapping’s output (design) to input (user).

asdict()
compare(other)
flavor = 'axis'
tag

string. Four letter tag for this axis. Some might be registered at the OpenType specification. Privately-defined axis tags must begin with an uppercase letter and use only uppercase letters or digits.

name

string. Name of the axis as it is used in the location dicts.

MutatorMath + Varlib.

labelNames

dict. When defining a non-registered axis, it will be necessary to define user-facing readable names for the axis. Keyed by xml:lang code. Values are required to be unicode strings, even if they only contain ASCII characters.

hidden

bool. Whether this axis should be hidden in user interfaces.

map

list of input / output values that can describe a warp of user space to design space coordinates. If no map values are present, it is assumed user space is the same as design space, as in [(minimum, minimum), (maximum, maximum)].

Varlib.

axisOrdering

STAT table field axisOrdering.

See: OTSpec STAT Axis Record

New in version 5.0.

axisLabels: List[AxisLabelDescriptor]

STAT table entries for Axis Value Tables format 1, 2, 3.

See: OTSpec STAT Axis Value Tables

New in version 5.0.

DiscreteAxisDescriptor

class fontTools.designspaceLib.DiscreteAxisDescriptor(*, tag=None, name=None, labelNames=None, values=None, default=None, hidden=False, map=None, axisOrdering=None, axisLabels=None)[source]

Container for discrete axis data.

Use this for axes that do not interpolate. The main difference from a continuous axis is that a continuous axis has a minimum and maximum, while a discrete axis has a list of values.

Example: an Italic axis with 2 stops, Roman and Italic, that are not compatible. The axis still allows to bind together the full font family, which is useful for the STAT table, however it can’t become a variation axis in a VF.

a2 = DiscreteAxisDescriptor()
a2.values = [0, 1]
a2.default = 0
a2.name = "Italic"
a2.tag = "ITAL"
a2.labelNames['fr'] = "Italique"
a2.map = [(0, 0), (1, -11)]
a2.axisOrdering = 2
a2.axisLabels = [
    AxisLabelDescriptor(name="Roman", userValue=0, elidable=True)
]
doc.addAxis(a2)

New in version 5.0.

flavor = 'axis'
default: float

The default value for this axis, i.e. when a new location is created, this is the value this axis will get in user space.

However, this default value is less important than in continuous axes:

  • it doesn’t define the “neutral” version of outlines from which deltas would apply, as this axis does not interpolate.

  • it doesn’t provide the reference glyph set for the designspace, as fonts at each value can have different glyph sets.

values: List[float]

List of possible values for this axis. Contrary to continuous axes, only the values in this list can be taken by the axis, nothing in-between.

map_forward(value)[source]

Maps value from axis mapping’s input to output.

Returns value unchanged if no mapping entry is found.

Note: for discrete axes, each value must have its mapping entry, if you intend that value to be mapped.

map_backward(value)[source]

Maps value from axis mapping’s output to input.

Returns value unchanged if no mapping entry is found.

Note: for discrete axes, each value must have its mapping entry, if you intend that value to be mapped.

asdict()
compare(other)
tag

string. Four letter tag for this axis. Some might be registered at the OpenType specification. Privately-defined axis tags must begin with an uppercase letter and use only uppercase letters or digits.

name

string. Name of the axis as it is used in the location dicts.

MutatorMath + Varlib.

labelNames

dict. When defining a non-registered axis, it will be necessary to define user-facing readable names for the axis. Keyed by xml:lang code. Values are required to be unicode strings, even if they only contain ASCII characters.

hidden

bool. Whether this axis should be hidden in user interfaces.

map

list of input / output values that can describe a warp of user space to design space coordinates. If no map values are present, it is assumed user space is the same as design space, as in [(minimum, minimum), (maximum, maximum)].

Varlib.

axisOrdering

STAT table field axisOrdering.

See: OTSpec STAT Axis Record

New in version 5.0.

axisLabels: List[AxisLabelDescriptor]

STAT table entries for Axis Value Tables format 1, 2, 3.

See: OTSpec STAT Axis Value Tables

New in version 5.0.

AxisLabelDescriptor

class fontTools.designspaceLib.AxisLabelDescriptor(*, name, userValue, userMinimum=None, userMaximum=None, elidable=False, olderSibling=False, linkedUserValue=None, labelNames=None)[source]

Container for axis label data.

Analogue of OpenType’s STAT data for a single axis (formats 1, 2 and 3). All values are user values. See: OTSpec STAT Axis value table, format 1, 2, 3

The STAT format of the Axis value depends on which field are filled-in, see getFormat()

New in version 5.0.

flavor = 'label'
userMinimum: Optional[float]

STAT field rangeMinValue (format 2).

userValue: float

STAT field value (format 1, 3) or nominalValue (format 2).

userMaximum: Optional[float]

STAT field rangeMaxValue (format 2).

name: str

Label for this axis location, STAT field valueNameID.

elidable: bool

STAT flag ELIDABLE_AXIS_VALUE_NAME.

See: OTSpec STAT Flags

olderSibling: bool

STAT flag OLDER_SIBLING_FONT_ATTRIBUTE.

See: OTSpec STAT Flags

linkedUserValue: Optional[float]

STAT field linkedValue (format 3).

labelNames: MutableMapping[str, str]

User-facing translations of this location’s label. Keyed by xml:lang code.

getFormat() int[source]

Determine which format of STAT Axis value to use to encode this label.

STAT Format

userValue

userMinimum

userMaximum

linkedUserValue

1

2

3

property defaultName: str

Return the English name from labelNames or the name.

asdict()
compare(other)

LocationLabelDescriptor

class fontTools.designspaceLib.LocationLabelDescriptor(*, name, userLocation, elidable=False, olderSibling=False, labelNames=None)[source]

Container for location label data.

Analogue of OpenType’s STAT data for a free-floating location (format 4). All values are user values.

See: OTSpec STAT Axis value table, format 4

New in version 5.0.

flavor = 'label'
name: str

Label for this named location, STAT field valueNameID.

userLocation: Dict[str, float]

Location in user coordinates along each axis.

If an axis is not mentioned, it is assumed to be at its default location.

See also

This may be only part of the full location. See: getFullUserLocation()

elidable: bool

STAT flag ELIDABLE_AXIS_VALUE_NAME.

See: OTSpec STAT Flags

olderSibling: bool

STAT flag OLDER_SIBLING_FONT_ATTRIBUTE.

See: OTSpec STAT Flags

labelNames: Dict[str, str]

User-facing translations of this location’s label. Keyed by xml:lang code.

property defaultName: str

Return the English name from labelNames or the name.

getFullUserLocation(doc: DesignSpaceDocument) Dict[str, float][source]

Get the complete user location of this label, by combining data from the explicit user location and default axis values.

New in version 5.0.

asdict()
compare(other)

RuleDescriptor

class fontTools.designspaceLib.RuleDescriptor(*, name=None, conditionSets=None, subs=None)[source]

Represents the rule descriptor element: a set of glyph substitutions to trigger conditionally in some parts of the designspace.

r1 = RuleDescriptor()
r1.name = "unique.rule.name"
r1.conditionSets.append([dict(name="weight", minimum=-10, maximum=10), dict(...)])
r1.conditionSets.append([dict(...), dict(...)])
r1.subs.append(("a", "a.alt"))
<!-- optional: list of substitution rules -->
<rules>
    <rule name="vertical.bars">
        <conditionset>
            <condition minimum="250.000000" maximum="750.000000" name="weight"/>
            <condition minimum="100" name="width"/>
            <condition minimum="10" maximum="40" name="optical"/>
        </conditionset>
        <sub name="cent" with="cent.alt"/>
        <sub name="dollar" with="dollar.alt"/>
    </rule>
</rules>
name

string. Unique name for this rule. Can be used to reference this rule data.

conditionSets

a list of conditionsets.

  • Each conditionset is a list of conditions.

  • Each condition is a dict with name, minimum and maximum keys.

subs

list of substitutions.

  • Each substitution is stored as tuples of glyphnames, e.g. (“a”, “a.alt”).

  • Note: By default, rules are applied first, before other text shaping/OpenType layout, as they are part of the Required Variation Alternates OpenType feature. See ref:rules-element § Attributes.

asdict()
compare(other)

Evaluating rules

fontTools.designspaceLib.evaluateRule(rule, location)[source]

Return True if any of the rule’s conditionsets matches the given location.

fontTools.designspaceLib.evaluateConditions(conditions, location)[source]

Return True if all the conditions matches the given location.

  • If a condition has no minimum, check for < maximum.

  • If a condition has no maximum, check for > minimum.

fontTools.designspaceLib.processRules(rules, location, glyphNames)[source]

Apply these rules at this location to these glyphnames.

Return a new list of glyphNames with substitutions applied.

  • rule order matters

SourceDescriptor

class fontTools.designspaceLib.SourceDescriptor(*, filename=None, path=None, font=None, name=None, location=None, designLocation=None, layerName=None, familyName=None, styleName=None, localisedFamilyName=None, copyLib=False, copyInfo=False, copyGroups=False, copyFeatures=False, muteKerning=False, muteInfo=False, mutedGlyphNames=None)[source]

Simple container for data related to the source

doc = DesignSpaceDocument()
s1 = SourceDescriptor()
s1.path = masterPath1
s1.name = "master.ufo1"
s1.font = defcon.Font("master.ufo1")
s1.location = dict(weight=0)
s1.familyName = "MasterFamilyName"
s1.styleName = "MasterStyleNameOne"
s1.localisedFamilyName = dict(fr="Caractère")
s1.mutedGlyphNames.append("A")
s1.mutedGlyphNames.append("Z")
doc.addSource(s1)
flavor = 'source'
property filename

string. A relative path to the source file, as it is in the document.

MutatorMath + VarLib.

property path

The absolute path, calculated from filename.

font

Any Python object. Optional. Points to a representation of this source font that is loaded in memory, as a Python object (e.g. a defcon.Font or a fontTools.ttFont.TTFont).

The default document reader will not fill-in this attribute, and the default writer will not use this attribute. It is up to the user of designspaceLib to either load the resource identified by filename and store it in this field, or write the contents of this field to the disk and make `filename point to that.

name

string. Optional. Unique identifier name for this source.

MutatorMath + Varlib.

designLocation

dict. Axis values for this source, in design space coordinates.

MutatorMath + Varlib.

This may be only part of the full design location. See getFullDesignLocation()

New in version 5.0.

layerName

string. The name of the layer in the source to look for outline data. Default None which means foreground.

familyName

string. Family name of this source. Though this data can be extracted from the font, it can be efficient to have it right here.

Varlib.

styleName

string. Style name of this source. Though this data can be extracted from the font, it can be efficient to have it right here.

Varlib.

localisedFamilyName

dict. A dictionary of localised family name strings, keyed by language code.

If present, will be used to build localized names for all instances.

New in version 5.0.

copyLib

bool. Indicates if the contents of the font.lib need to be copied to the instances.

MutatorMath.

Deprecated since version 5.0.

copyInfo

bool. Indicates if the non-interpolating font.info needs to be copied to the instances.

MutatorMath.

Deprecated since version 5.0.

copyGroups

bool. Indicates if the groups need to be copied to the instances.

MutatorMath.

Deprecated since version 5.0.

copyFeatures

bool. Indicates if the feature text needs to be copied to the instances.

MutatorMath.

Deprecated since version 5.0.

muteKerning

bool. Indicates if the kerning data from this source needs to be muted (i.e. not be part of the calculations).

MutatorMath only.

muteInfo

bool. Indicated if the interpolating font.info data for this source needs to be muted.

MutatorMath only.

mutedGlyphNames

list. Glyphnames that need to be muted in the instances.

MutatorMath only.

property location

dict. Axis values for this source, in design space coordinates.

MutatorMath + Varlib.

Deprecated since version 5.0: Use the more explicit alias for this property designLocation.

setFamilyName(familyName, languageCode='en')[source]

Setter for localisedFamilyName

New in version 5.0.

getFamilyName(languageCode='en')[source]

Getter for localisedFamilyName

New in version 5.0.

getFullDesignLocation(doc: DesignSpaceDocument) Dict[str, Union[float, Tuple[float, float]]][source]

Get the complete design location of this source, from its designLocation and the document’s axis defaults.

New in version 5.0.

asdict()
compare(other)

VariableFontDescriptor

class fontTools.designspaceLib.VariableFontDescriptor(*, name, filename=None, axisSubsets=None, lib=None)[source]

Container for variable fonts, sub-spaces of the Designspace.

Use-cases:

  • From a single DesignSpace with discrete axes, define 1 variable font per value on the discrete axes. Before version 5, you would have needed 1 DesignSpace per such variable font, and a lot of data duplication.

  • From a big variable font with many axes, define subsets of that variable font that only include some axes and freeze other axes at a given location.

New in version 5.0.

flavor = 'variable-font'
name: str

string, required. Name of this variable to identify it during the build process and from other parts of the document, and also as a filename in case the filename property is empty.

VarLib.

property filename

string, optional. Relative path to the variable font file, as it is in the document. The file may or may not exist.

If not specified, the name will be used as a basename for the file.

axisSubsets: List[Union[RangeAxisSubsetDescriptor, ValueAxisSubsetDescriptor]]

Axis subsets to include in this variable font.

If an axis is not mentioned, assume that we only want the default location of that axis (same as a ValueAxisSubsetDescriptor).

lib: MutableMapping[str, Any]

Custom data associated with this variable font.

asdict()
compare(other)

RangeAxisSubsetDescriptor

class fontTools.designspaceLib.RangeAxisSubsetDescriptor(*, name, userMinimum=-inf, userDefault=None, userMaximum=inf)[source]

Subset of a continuous axis to include in a variable font.

New in version 5.0.

flavor = 'axis-subset'
name: str

Name of the AxisDescriptor to subset.

userMinimum: float

New minimum value of the axis in the target variable font. If not specified, assume the same minimum value as the full axis. (default = -math.inf)

userDefault: Optional[float]

New default value of the axis in the target variable font. If not specified, assume the same default value as the full axis. (default = None)

userMaximum: float

New maximum value of the axis in the target variable font. If not specified, assume the same maximum value as the full axis. (default = math.inf)

asdict()
compare(other)

ValueAxisSubsetDescriptor

class fontTools.designspaceLib.ValueAxisSubsetDescriptor(*, name, userValue)[source]

Single value of a discrete or continuous axis to use in a variable font.

New in version 5.0.

flavor = 'axis-subset'
name: str

Name of the AxisDescriptor or DiscreteAxisDescriptor to “snapshot” or “freeze”.

userValue: float

Value in user coordinates at which to freeze the given axis.

asdict()
compare(other)

InstanceDescriptor

class fontTools.designspaceLib.InstanceDescriptor(*, filename=None, path=None, font=None, name=None, location=None, locationLabel=None, designLocation=None, userLocation=None, familyName=None, styleName=None, postScriptFontName=None, styleMapFamilyName=None, styleMapStyleName=None, localisedFamilyName=None, localisedStyleName=None, localisedStyleMapFamilyName=None, localisedStyleMapStyleName=None, glyphs=None, kerning=True, info=True, lib=None)[source]

Simple container for data related to the instance

i2 = InstanceDescriptor()
i2.path = instancePath2
i2.familyName = "InstanceFamilyName"
i2.styleName = "InstanceStyleName"
i2.name = "instance.ufo2"
# anisotropic location
i2.designLocation = dict(weight=500, width=(400,300))
i2.postScriptFontName = "InstancePostscriptName"
i2.styleMapFamilyName = "InstanceStyleMapFamilyName"
i2.styleMapStyleName = "InstanceStyleMapStyleName"
i2.lib['com.coolDesignspaceApp.specimenText'] = 'Hamburgerwhatever'
doc.addInstance(i2)
flavor = 'instance'
property filename

string. Relative path to the instance file, as it is in the document. The file may or may not exist.

MutatorMath + VarLib.

property path

string. Absolute path to the instance file, calculated from the document path and the string in the filename attr. The file may or may not exist.

MutatorMath.

font

Same as SourceDescriptor.font

name

string. Unique identifier name of the instance, used to identify it if it needs to be referenced from elsewhere in the document.

locationLabel

Name of a LocationLabelDescriptor. If provided, the instance should have the same location as the LocationLabel.

New in version 5.0.

designLocation: Dict[str, Union[float, Tuple[float, float]]]

dict. Axis values for this instance, in design space coordinates.

MutatorMath + Varlib.

See also

This may be only part of the full location. See: getFullDesignLocation() getFullUserLocation()

New in version 5.0.

userLocation: Dict[str, float]

dict. Axis values for this instance, in user space coordinates.

MutatorMath + Varlib.

See also

This may be only part of the full location. See: getFullDesignLocation() getFullUserLocation()

New in version 5.0.

familyName

string. Family name of this instance.

MutatorMath + Varlib.

styleName

string. Style name of this instance.

MutatorMath + Varlib.

postScriptFontName

string. Postscript fontname for this instance.

MutatorMath + Varlib.

styleMapFamilyName

string. StyleMap familyname for this instance.

MutatorMath + Varlib.

styleMapStyleName

string. StyleMap stylename for this instance.

MutatorMath + Varlib.

localisedFamilyName

dict. A dictionary of localised family name strings, keyed by language code.

localisedStyleName

dict. A dictionary of localised stylename strings, keyed by language code.

localisedStyleMapFamilyName

A dictionary of localised style map familyname strings, keyed by language code.

localisedStyleMapStyleName

A dictionary of localised style map stylename strings, keyed by language code.

glyphs

dict for special master definitions for glyphs. If glyphs need special masters (to record the results of executed rules for example).

MutatorMath.

Deprecated since version 5.0: Use rules or sparse sources instead.

kerning

bool. Indicates if this instance needs its kerning calculated.

MutatorMath.

Deprecated since version 5.0.

info

bool. Indicated if this instance needs the interpolating font.info calculated.

Deprecated since version 5.0.

lib

Custom data associated with this instance.

property location

dict. Axis values for this instance.

MutatorMath + Varlib.

Deprecated since version 5.0: Use the more explicit alias for this property designLocation.

setStyleName(styleName, languageCode='en')[source]

These methods give easier access to the localised names.

getStyleName(languageCode='en')[source]
setFamilyName(familyName, languageCode='en')[source]
getFamilyName(languageCode='en')[source]
setStyleMapStyleName(styleMapStyleName, languageCode='en')[source]
getStyleMapStyleName(languageCode='en')[source]
setStyleMapFamilyName(styleMapFamilyName, languageCode='en')[source]
getStyleMapFamilyName(languageCode='en')[source]
clearLocation(axisName: Optional[str] = None)[source]

Clear all location-related fields. Ensures that :attr:designLocation and :attr:userLocation are dictionaries (possibly empty if clearing everything).

In order to update the location of this instance wholesale, a user should first clear all the fields, then change the field(s) for which they have data.

instance.clearLocation()
instance.designLocation = {'Weight': (34, 36.5), 'Width': 100}
instance.userLocation = {'Opsz': 16}

In order to update a single axis location, the user should only clear that axis, then edit the values:

instance.clearLocation('Weight')
instance.designLocation['Weight'] = (34, 36.5)
Parameters

axisName – if provided, only clear the location for that axis.

New in version 5.0.

getLocationLabelDescriptor(doc: DesignSpaceDocument) Optional[LocationLabelDescriptor][source]

Get the LocationLabelDescriptor instance that matches this instances’s locationLabel.

Raises if the named label can’t be found.

New in version 5.0.

getFullDesignLocation(doc: DesignSpaceDocument) Dict[str, Union[float, Tuple[float, float]]][source]

Get the complete design location of this instance, by combining data from the various location fields, default axis values and mappings, and top-level location labels.

The source of truth for this instance’s location is determined for each axis independently by taking the first not-None field in this list:

  • locationLabel: the location along this axis is the same as the matching STAT format 4 label. No anisotropy.

  • designLocation[axisName]: the explicit design location along this axis, possibly anisotropic.

  • userLocation[axisName]: the explicit user location along this axis. No anisotropy.

  • axis.default: default axis value. No anisotropy.

New in version 5.0.

getFullUserLocation(doc: DesignSpaceDocument) Dict[str, float][source]

Get the complete user location for this instance.

New in version 5.0.

asdict()
compare(other)

Subclassing descriptors

The DesignSpaceDocument can take subclassed Reader and Writer objects. This allows you to work with your own descriptors. You could subclass the descriptors. But as long as they have the basic attributes the descriptor does not need to be a subclass.

class MyDocReader(BaseDocReader):
    axisDescriptorClass = MyAxisDescriptor
    discreteAxisDescriptorClass = MyDiscreteAxisDescriptor
    axisLabelDescriptorClass = MyAxisLabelDescriptor
    locationLabelDescriptorClass = MyLocationLabelDescriptor
    ruleDescriptorClass = MyRuleDescriptor
    sourceDescriptorClass = MySourceDescriptor
    variableFontsDescriptorClass = MyVariableFontDescriptor
    valueAxisSubsetDescriptorClass = MyValueAxisSubsetDescriptor
    rangeAxisSubsetDescriptorClass = MyRangeAxisSubsetDescriptor
    instanceDescriptorClass = MyInstanceDescriptor

class MyDocWriter(BaseDocWriter):
    axisDescriptorClass = MyAxisDescriptor
    discreteAxisDescriptorClass = MyDiscreteAxisDescriptor
    axisLabelDescriptorClass = MyAxisLabelDescriptor
    locationLabelDescriptorClass = MyLocationLabelDescriptor
    ruleDescriptorClass = MyRuleDescriptor
    sourceDescriptorClass = MySourceDescriptor
    variableFontsDescriptorClass = MyVariableFontDescriptor
    valueAxisSubsetDescriptorClass = MyValueAxisSubsetDescriptor
    rangeAxisSubsetDescriptorClass = MyRangeAxisSubsetDescriptor
    instanceDescriptorClass = MyInstanceDescriptor

myDoc = DesignSpaceDocument(MyDocReader, MyDocWriter)

Helper modules

fontTools.designspaceLib.split

See Scripting > Working with DesignSpace version 5 for more information.

Allows building all the variable fonts of a DesignSpace version 5 by splitting the document into interpolable sub-space, then into each VF.

fontTools.designspaceLib.split.convert5to4(doc: DesignSpaceDocument) Dict[str, DesignSpaceDocument][source]

Convert each variable font listed in this document into a standalone format 4 designspace. This can be used to compile all the variable fonts from a format 5 designspace using tools that only know about format 4.

New in version 5.0.

fontTools.designspaceLib.split.defaultMakeInstanceFilename(doc: DesignSpaceDocument, instance: InstanceDescriptor, statNames: StatNames) str[source]

Default callable to synthesize an instance filename when makeNames=True, for instances that don’t specify an instance name in the designspace. This part of the name generation can be overriden because it’s not specified by the STAT table.

fontTools.designspaceLib.split.splitInterpolable(doc: ~fontTools.designspaceLib.DesignSpaceDocument, makeNames: bool = True, expandLocations: bool = True, makeInstanceFilename: ~typing.Callable[[~fontTools.designspaceLib.DesignSpaceDocument, ~fontTools.designspaceLib.InstanceDescriptor, ~fontTools.designspaceLib.statNames.StatNames], str] = <function defaultMakeInstanceFilename>) Iterator[Tuple[Dict[str, float], DesignSpaceDocument]][source]

Split the given DS5 into several interpolable sub-designspaces. There are as many interpolable sub-spaces as there are combinations of discrete axis values.

E.g. with axes:
  • italic (discrete) Upright or Italic

  • style (discrete) Sans or Serif

  • weight (continuous) 100 to 900

There are 4 sub-spaces in which the Weight axis should interpolate: (Upright, Sans), (Upright, Serif), (Italic, Sans) and (Italic, Serif).

The sub-designspaces still include the full axis definitions and STAT data, but the rules, sources, variable fonts, instances are trimmed down to only keep what falls within the interpolable sub-space.

Parameters
  • makeNames (-) – Whether to compute the instance family and style names using the STAT data.

  • expandLocations (-) – Whether to turn all locations into “full” locations, including implicit default axis values where missing.

  • makeInstanceFilename (-) – Callable to synthesize an instance filename when makeNames=True, for instances that don’t specify an instance name in the designspace. This part of the name generation can be overridden because it’s not specified by the STAT table.

New in version 5.0.

fontTools.designspaceLib.split.splitVariableFonts(doc: ~fontTools.designspaceLib.DesignSpaceDocument, makeNames: bool = False, expandLocations: bool = False, makeInstanceFilename: ~typing.Callable[[~fontTools.designspaceLib.DesignSpaceDocument, ~fontTools.designspaceLib.InstanceDescriptor, ~fontTools.designspaceLib.statNames.StatNames], str] = <function defaultMakeInstanceFilename>) Iterator[Tuple[str, DesignSpaceDocument]][source]

Convert each variable font listed in this document into a standalone designspace. This can be used to compile all the variable fonts from a format 5 designspace using tools that can only deal with 1 VF at a time.

Parameters
  • makeNames (-) – Whether to compute the instance family and style names using the STAT data.

  • expandLocations (-) – Whether to turn all locations into “full” locations, including implicit default axis values where missing.

  • makeInstanceFilename (-) – Callable to synthesize an instance filename when makeNames=True, for instances that don’t specify an instance name in the designspace. This part of the name generation can be overridden because it’s not specified by the STAT table.

New in version 5.0.

fontTools.designspaceLib.stat

fontTools.designspaceLib.statNames

Compute name information for a given location in user-space coordinates using STAT data. This can be used to fill-in automatically the names of an instance:

instance = doc.instances[0]
names = getStatNames(doc, instance.getFullUserLocation(doc))
print(names.styleNames)
class fontTools.designspaceLib.statNames.StatNames(familyNames: Dict[str, str], styleNames: Dict[str, str], postScriptFontName: Optional[str], styleMapFamilyNames: Dict[str, str], styleMapStyleName: Optional[str])[source]

Name data generated from the STAT table information.

fontTools.designspaceLib.statNames.getStatNames(doc: DesignSpaceDocument, userLocation: Dict[str, float]) StatNames[source]

Compute the family, style, PostScript names of the given userLocation using the document’s STAT information.

Also computes localizations.

If not enough STAT data is available for a given name, either its dict of localized names will be empty (family and style names), or the name will be None (PostScript name).

New in version 5.0.