The mojo module includes a handy FontsList object which makes it easy to sort a list of fonts by any font info attribute.

Sorting by style name (alphabetically)

allFonts = AllFonts()
allFonts.sortBy('styleName')

for f in allFonts:
    print(f)
<RFont 'RoboType Bold' path='/RFTextBold.ufo' at 4596479200>
<RFont 'RoboType Bold Italic' path='/RFTextBoldItalic.ufo' at 4596478528>
<RFont 'RoboType Italic' path='/RFTextItalic.ufo' at 4596481888>
<RFont 'RoboType Mono' path='/RFTextMono.ufo' at 4596481216>
<RFont 'RoboType Narrow Bold' path='/RFNarrowBold.ufo' at 4596479144>
<RFont 'RoboType Narrow Bold Italic' path='/RFNarrowBoldItalic.ufo' at 4596480432>
<RFont 'RoboType Roman' path='/RFTextRoman.ufo' at 4596478192>

Sorting by weight value

# continued from previous example

allFonts.sortBy('openTypeOS2WeightClass')

for f in allFonts:
    print(f.info.openTypeOS2WeightClass, f)
350 <RFont 'RoboType Mono' path='/RFTextMono.ufo' at 4596481216>
400 <RFont 'RoboType Italic' path='/RFTextItalic.ufo' at 4596481888>
400 <RFont 'RoboType Roman' path='/RFTextRoman.ufo' at 4596478192>
700 <RFont 'RoboType Bold' path='/RFTextBold.ufo' at 4596479200>
700 <RFont 'RoboType Bold Italic' path='/RFTextBoldItalic.ufo' at 4596478528>
700 <RFont 'RoboType Narrow Bold' path='/RFNarrowBold.ufo' at 4596479144>
700 <RFont 'RoboType Narrow Bold Italic' path='/RFNarrowBoldItalic.ufo' at 4596480432>

Sorting by width value

# continued from previous example

allFonts.sortBy('openTypeOS2WidthClass')

for f in allFonts:
    print(f.info.openTypeOS2WidthClass, f)
3 <RFont 'RoboType Narrow Bold' path='/RFNarrowBold.ufo' at 4596479144>
3 <RFont 'RoboType Narrow Bold Italic' path='/RFNarrowBoldItalic.ufo' at 4596480432>
5 <RFont 'RoboType Mono' path='/RFTextMono.ufo' at 4596481216>
5 <RFont 'RoboType Italic' path='/RFTextItalic.ufo' at 4596481888>
5 <RFont 'RoboType Roman' path='/RFTextRoman.ufo' at 4596478192>
5 <RFont 'RoboType Bold' path='/RFTextBold.ufo' at 4596479200>
5 <RFont 'RoboType Bold Italic' path='/RFTextBoldItalic.ufo' at 4596478528>

Sorting using multiple values

It is also possible to combine several sorting attributes.

# continued from previous example
allFonts.sortBy(['isItalic', 'styleName'])

for f in allFonts:
    print(f.info.familyName, f.info.styleName, f.info.italicAngle)
RoboType Bold Italic -6
RoboType Italic -6.0
RoboType Narrow Bold Italic -6.0
RoboType Bold None
RoboType Mono None
RoboType Narrow Bold None
RoboType Roman None

Remember to provide the sorting keys as list/tuple! Otherwise you’ll risk some weird and obscure results 🔮

Last edited on 01/09/2021