Music Theory
musictheory is a package designed to investigate the question "Which chords go with which scales?" A couple of years ago, the author was very interested and obsessed in the question, and decided to put his Python skills to the task. Along the way, the musictheory package was redesigned to be more flexible and extendible.
The package has roughly the same philosophy as Music Set Theory but uses different terminology.
Documentation
The source code contains an excess of documentation strings. Hopefully it makes things clearer. The sections below map the modules, types, and main call paths.
The central question the library answers is: given a scale and a key, which named chords (sonorities) sit on each degree?
temperament (WestTemp)
└── registers noteseq / noteseq_scale / noteseq_chord
└── chordgenerator.populate_scale_chords → HTML via chordgentable
Package layout
temperament— Defines pitch classes, note spelling, and a registry of scales and chords.scales— Provides the basenoteseqclass, a scale subclass, and the built-in scales and modes.chords— Provides a chord subclass, the Western chord catalogue, and spelling patterns.chordgenerator— Builds scale-to-chord tables and renders them as HTML.musutility— Supplies small sequence helpers used throughout the package.
Chord registration runs when chords is imported (or when
chordgenerator imports it). Scales register themselves when scales
is imported.
temperament
Constants (selection)
- Accidentals:
M_SHARP,M_FLAT,M_NATURAL, the doubles and halves, the ASCII forms (MNU_*), and theNOTESYMBOL_*maps. - Sequence kinds:
NSEQ_SCALEandNSEQ_CHORD. - 12-TET neutrals:
CHROM_NAT_NOTES,CHROM_NAT_NOTE_POS, andCHROM_SIZE. - Built-in instance:
WestTempis the Western 12-tone temperament with the natural letters C–B.
seq_dict
The seq_dict class acts as a multi-key dictionary for registered
note-sequence objects. It allows lookups by name, by abbreviation, and
by the sorted semitone pattern.
add_elem(...)— Registers a sequence under its names, abbreviations, and pattern.check_nseqby_name/abbrv/seqpos/subdict— Checks whether a matching entry is present.get_nseqby_name/abbrv/seqpos— Looks up a registered object.
temperament
A temperament defines how many pitch classes there are, what the
natural letter names are, and where those letters sit chromatically. It
also owns seq_maps, which keeps separate maps for scales and for
chords.
note_parse(key)— Splits a note name into a natural letter and an accidental offset.get_pos_of_key(key)— Returns the chromatic position of a named note.get_key_of_pos(pos, desired_nat=None, ...)— Spells a position as a note name, optionally forcing a preferred letter.get_note_sequence(key, pos_seq, nat_pos_seq=None)— Returns note names for intervals from key;nat_pos_seqdrives the letter spelling.get_keyseq_notes(note_seq)— Performs the inverse: notes become[base_key, relative positions].add_elem/check_*/get_nseqby_*— Delegates to the appropriateseq_dict.
Function
un_unicode_accdtls(str_note)turns Unicode accidentals into ASCII forms (♯→#, and so on).
scales
noteseq
This represents a pattern of notes — a scale or a chord — each with a
specified position from a base key. The sound is given by relative
semitone positions (nseq_posn); the spelling is given by parallel
letter offsets (nseq_nat_posns). The same model is used for both
scales and chords.
-
nseq_posn— The sounding intervals; for example, a major triad is[0, 4, 7]. -
nseq_nat_posns— The letter spelling; for a triad this is[0, 2, 4](1st, 3rd, and 5th letters). -
register_with_temp()— Registers this pattern on its temperament so that it can be looked up by name, abbreviation, or pattern. -
get_notes_for_key(key, rotate_by=0, indices=None)— Returns the spelled notes in key, optionally rotated and sliced (multislice). The slice modulus islen(nseq_posn)(7 for Major, 8 for Diminished). -
get_posn_for_offset(rotate_by=0, indices=None, raz=False)— Applies the same rotate and slice to the semitone positions; ifrazisTrue, the result is rezeroed so that the first kept tone is0.
noteseq_scale
This is a specialisation of noteseq used for scales. The constructor
can take mode names and registers each rotation as its own scale on the
temperament.
Built-in scales (examples)
These are created at import time on WestTemp:
MajorScale(plus the modes inMAJORMODES)MelMinorScale,HarmMinorScale,HarmMajorScaleDiscMinorScale,HungarianScaleDiminishedScale(8 notes; Whole-Half / Half-Whole mode names live inDIMINISHEDMODES)
Related constants include HEPT_NAT_POSNS, OCT_NAT_POSNS, the
*_NOTE_POS lists, and the mode-name lists.
chords
noteseq_chord
This is a specialisation of noteseq used exclusively for chords
(NSEQ_CHORD). It uses the same spelling and position model as scales.
CHORDTYPE_DICT
This is a spelling catalogue only, used when registering chords: each
pattern name maps onto an nseq_nat_posns list (for example,
"Triad" → [0, 2, 4], "Seventh" → [0, 2, 4, 6]).
It is not used for scale-table row slicing; see SONORITY_SLICES in
chordgenerator for that.
generate_west_chords()
This builds the Western chord catalogue (triads, sevenths, suspensions,
adds, diminished stacks, and so on), registers each chord on
WestTemp, and returns the list. Importing the module runs this once
and stores the result in ourchords.
chordgenerator
This module turns a named scale and a key into a table of sonorities (rows) by scale degrees (columns), and can render that table as HTML.
Sonority catalogues (table rows)
SONORITY_SLICES— Maps each display label onto the 0-based degree indices to take from the scale.HEPTATONIC_SONORITIES— Lists the row labels for 7-note scales, in display order.HEPTATONIC_SONORITIES_RESERVE— Holds parked heptatonic rows that are not used in the tables.DIMINISHED_SONORITIES— Lists the row labels for 8-note diminished scales.DIMINISHED_SONORITIES_RESERVE— Holds parked octatonic rows that are not used in the tables.OCTATONIC_SONORITIES— Is an alias ofDIMINISHED_SONORITIES.
Sonority labels look like 1–3–5 (Triad chords): a degree pattern
plus a gloss.
sonorities_for_nseq_len(n, priority="all")— Returns the heptatonic list ifnis not 8, otherwise the diminished list; an optionalessential/important/allfilter may be applied.sonorities_for_scale(scale, priority="all")— Does the same, usinglen(scale.nseq_posn).filter_sonorities_by_priority(labels, level)— Keeps labels whose priority is at mostessential(1),important(2), orall(3).SONORITY_PRIORITY— Maps each display label onto a priority band of 1, 2, or 3.SONORITY_PRIORITY_LEVELS— Mapsessential/important/allonto a maximum priority.
Table model
scale_chords— Represents all the chords associated with a scale. This is used to make a tabular representation (scale name, key, full note list, Roman headers, androws).scale_chordrow— Represents one sonority row (chord_typelabel plus a list ofnotescells).scale_chordcell— Represents one cell: a full name, an abbreviation, and a note list (empty names if unmatched).
Building and rendering
populate_scale_chords(scale_name, key, possiblechords=None)— Returns ascale_chordstable: for each sonority and degree it slices notes and positions, then looks up the chord viaWestTemp.get_nseqby_seqpos.chordgentable(scales, ...)— Generates an HTML table representation; factories can customise the<th>/<td>/ caption output (as used by the Django chordgenerator app).int_to_roman/make_roman_numeral_list— Produce the Roman-numeral column headers (I,II, …).makebaserep— Provides an optional numeric degree spelling when key is an integer base.
The print-mode constants PRINT_ABBRV, PRINT_FNAME, and
PRINT_BOTH exist for callers that choose name versus abbreviation
display.
musutility
These are generic sequence tools with no music-domain knowledge of their own:
rotate(seq, offset)— Rotates a sequence to the left by offset places.rotate_and_zero(seq, offset, mod)— Rotates the sequence, then shifts values so that the first element is0(modulo mod when mod is non-zero).multislice(seq, indices, mod=0, offset=0)— Gathers elements by index after an optional rotate; indices may be taken modulo mod.scalar_addition(seq, scalar)— Adds a constant to each element.norm_seq(seq, mod)— Returns the sorted unique residues modulo mod.enl_seq(seq_of_seq, otherentries)— Appends entries in a Cartesian fashion (used when expanding chord-tone patterns).seqtostr/repseq— Produce comma-separated string forms of a sequence.
Typical usage sketch
from musictheory.chordgenerator import populate_scale_chords, chordgentable
table = populate_scale_chords("Major", "C")
# table.rows[i].chord_type → e.g. "1–3–5 (Triad-like chords)"
# table.rows[i].notes[j] → scale_chordcell for degree j
html = chordgentable([table])
# Or look up patterns directly:
from musictheory.temperament import WestTemp, NSEQ_SCALE, NSEQ_CHORD
scale = WestTemp.get_nseqby_name("Dorian", NSEQ_SCALE)
chord = WestTemp.get_nseqby_seqpos([0, 3, 7], NSEQ_CHORD) # minor triad shape
Mental model: two “pattern” dictionaries
CHORDTYPE_DICT(chords) — Used for spelling when registering a chord (for example,"Triad"→[0, 2, 4]).SONORITY_SLICES(chordgenerator) — Used for slicing a scale for a table row (for example,"1–3–5 (Triad-like chords)"→[0, 2, 4]).
Cell chord qualities (Major, Minor, dim7, and so on) come from matching the sliced semitone shapes against the registered chord map — not from the row label itself.
Installation
pip install musictheory
Testing
Testing can be performed by executing the following code in the setup directory:
python -m test.test_all
License
The software has been released using a 3-clause Berkeley Software
Distribution (BSD) license. See LICENSE.txt for more information.
Versions
- 0.1 (May 1st 2011) - Create setup script for files.
- 0.2 (May 11th 2011) - Remove bugs for working with chordgenerator.
- 0.3 (June 6th 2011) - Add license information. Add more scales.
- 0.4 (April 24th 2013) - Try to make a half-decent PyPI package.
- 0.5 (August 14th 2014) - Add some experimental suspended chords.
- 0.6 (December 6th 2020) - Updated for Python 3.0 compatibility.
- 0.7 (October 30th 2026) - General Pyright code cleanup; sonority sets for heptatonic vs octatonic (diminished) scales;
chordgentablevariable columns and extension hooks.
Copyright
The musictheory package is copyright (c) 2008-2026 Peter Murphy peterkmurphy@gmail.com.
Metadata
Release files for musictheory 0.7
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| musictheory-0.7.tar.gz | 43.4 kB | Without provenance | Details for musictheory-0.7.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| musictheory-0.7-py3-none-any.whl | Python 3 | none | any | Details for musictheory-0.7-py3-none-any.whl |
Total release size: 80.8 kB
Release files / musictheory-0.7.tar.gz
| Download URL | musictheory-0.7.tar.gz |
|---|---|
| Size | 43.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
39e860f1cc1f2293b9806522bc3566bfe4411e4e9c457a63062491814051fbab
|
|
BLAKE2b-256 checksum How to use checksums |
b60b7a85b769c81bfbc16f0ba80857ce9b7795a563cc5d53e497bc95dcaab229
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.7
|
Release files / musictheory-0.7-py3-none-any.whl
| Download URL | musictheory-0.7-py3-none-any.whl |
|---|---|
| Size | 37.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4da53c204b45cd51d2ca780521c5afd25e2be76860ac711266736990e5dc4b77
|
|
BLAKE2b-256 checksum How to use checksums |
6071633ed28f8eab222f459b1cbebbbbf80496ff2a22746b7e3ed43331144166
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.7
|
Security for musictheory 0.7
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.