Iterate Through Glyphs Using FontForge Python

This guide explains how to iterate through all the glyphs in a font file using FontForge’s built-in Python module (fontforge). You will learn the primary method for accessing glyph objects, how to read glyph attributes during iteration, and how to apply batch modifications before saving your font.

Opening the Font

To work with glyphs in Python, first import the fontforge library and open your target font file using fontforge.open().

import fontforge

# Open the font file
font = fontforge.open("path/to/your-font.ttf")

Using font.glyphs() for Iteration

The most efficient and direct way to loop through every defined glyph is the font.glyphs() generator method. This returns an iterator of glyph objects, automatically skipping unassigned or empty encoding slots.

import fontforge

font = fontforge.open("path/to/your-font.ttf")

for glyph in font.glyphs():
    # Access glyph properties
    name = glyph.glyphname
    codepoint = glyph.unicode
    width = glyph.width

    print(f"Name: {name} | Unicode: {hex(codepoint) if codepoint != -1 else 'None'} | Width: {width}")

Modifying Glyphs in a Loop

Because the loop yields mutable glyph references, you can perform batch transformations, adjust metrics, or clear specific layers directly within the iteration.

import fontforge

font = fontforge.open("path/to/your-font.ttf")

for glyph in font.glyphs():
    # Example: Increase the right side bearing/width by 10 units
    glyph.width += 10
    
    # Example: Auto-hint defined glyphs
    glyph.autoHint()

# Save the modifications
font.generate("path/to/modified-font.ttf")
font.close()

Iterating via Selection

If you only want to iterate through a subset of glyphs or ensure you include empty slots mapped to an encoding, use the font's selection interface:

import fontforge

font = fontforge.open("path/to/your-font.ttf")

# Select all glyphs in the encoding
font.selection.all()

for glyph_name in font.selection.byGlyphs:
    glyph = font[glyph_name]
    # Process the selected glyph
    print(glyph.glyphname)

font.close()

Key Considerations

  • Undefined Unicode: Glyphs without a assigned Unicode value return -1 for glyph.unicode.
  • Memory Management: When working with large fonts or running loops over multiple files, explicitly call font.close() to free allocated memory.