This module defines objects for representing key signatures as well as key areas. The KeySignature is used in Measure objects for defining notated key signatures.

The Key object is a fuller representation not just of a key signature but also of the key of a region.


class music21.key.KeySignature(sharps: Optional[int] = 0)

A KeySignature object specifies the signature to be used for a piece; it takes in zero or one arguments. The only argument is an int giving the number of sharps, or if negative the number of flats.

If you are starting with the name of a key, see the Key object.

>>> A = key.KeySignature(3)
>>> A
<music21.key.KeySignature of 3 sharps>
>>> Eflat = key.KeySignature(-3)
>>> Eflat
<music21.key.KeySignature of 3 flats>

If you want to get a real Key, then use the Key object instead:

>>> illegal = key.KeySignature('c#')
Traceback (most recent call last):
music21.key.KeySignatureException: Cannot get a KeySignature from this
    "number" of sharps: 'c#'; did you mean to use a key.Key() object instead?
>>> legal = key.Key('c#')
>>> legal.sharps
>>> legal
<music21.key.Key of c# minor>

To set a non-traditional Key Signature, create a KeySignature object with sharps=None, and then set the alteredPitches list:

>>> unusual = key.KeySignature(sharps=None)
>>> unusual.alteredPitches = ['E-', 'G#']
>>> unusual
<music21.key.KeySignature of pitches: [E-, G#]>
>>> unusual.isNonTraditional

To set a pitch as displayed in a particular octave, create a non-traditional KeySignature and then set pitches with octaves:

>>> unusual = key.KeySignature(sharps=None)
>>> unusual.alteredPitches = ['F#4']
>>> unusual
<music21.key.KeySignature of pitches: [F#4]>

If the accidental applies to all octaves but is being displayed differently then you are done, but if you want them to apply only to the octave displayed in then set .accidentalsApplyOnlyToOctave to True:

>>> unusual.accidentalsApplyOnlyToOctave
>>> unusual.accidentalsApplyOnlyToOctave = True

Changed in v.7 – sharps defaults to 0 (key of no flats/sharps) rather than None for nontraditional keys.

KeySignature bases

KeySignature read-only properties


Returns bool if this is a non-traditional KeySignature:

>>> g = key.KeySignature(3)
>>> g.isNonTraditional
>>> g = key.KeySignature(sharps=None)
>>> g.alteredPitches = [pitch.Pitch('E`')]
>>> g.isNonTraditional
>>> g
<music21.key.KeySignature of pitches: [E`]>
>>> g.accidentalByStep('E')
<music21.pitch.Accidental half-flat>

Read-only properties inherited from Music21Object:

Read-only properties inherited from ProtoM21Object:

KeySignature read/write properties


Return or set a list of music21.pitch.Pitch objects that are altered by this KeySignature. That is, all Pitch objects that will receive an accidental.

>>> a = key.KeySignature(3)
>>> a.alteredPitches
[<music21.pitch.Pitch F#>, <music21.pitch.Pitch C#>, <music21.pitch.Pitch G#>]
>>> b = key.KeySignature(1)
>>> b.alteredPitches
[<music21.pitch.Pitch F#>]
>>> c = key.KeySignature(9)
>>> [str(p) for p in c.alteredPitches]
['F#', 'C#', 'G#', 'D#', 'A#', 'E#', 'B#', 'F##', 'C##']
>>> d = key.KeySignature(-3)
>>> d.alteredPitches
[<music21.pitch.Pitch B->, <music21.pitch.Pitch E->, <music21.pitch.Pitch A->]
>>> e = key.KeySignature(-1)
>>> e.alteredPitches
[<music21.pitch.Pitch B->]
>>> f = key.KeySignature(-6)
>>> [str(p) for p in f.alteredPitches]
['B-', 'E-', 'A-', 'D-', 'G-', 'C-']
>>> g = key.KeySignature(-8)
>>> [str(p) for p in g.alteredPitches]
['B-', 'E-', 'A-', 'D-', 'G-', 'C-', 'F-', 'B--']

Non-standard, non-traditional key signatures can set their own altered pitches cache.

>>> nonTrad = key.KeySignature(sharps=None)
>>> nonTrad.alteredPitches = ['B-', 'F#', 'E-', 'G#']
>>> nonTrad.alteredPitches
[<music21.pitch.Pitch B->,
 <music21.pitch.Pitch F#>,
 <music21.pitch.Pitch E->,
 <music21.pitch.Pitch G#>]

Get or set the number of sharps. If the number is negative then it sets the number of flats. Equivalent to musicxml’s ‘fifths’ attribute.

>>> ks1 = key.KeySignature(2)
>>> ks1.sharps
>>> ks1.sharps = -4
>>> ks1
<music21.key.KeySignature of 4 flats>

Can be set to None for a non-traditional key signature

Read/write properties inherited from Music21Object:

KeySignature methods


two KeySignatures are equal if their sharps are equal.


Given a step (C, D, E, F, etc.) return the accidental for that note in this key (using the natural minor for minor) or None if there is none.

>>> g = key.KeySignature(1)
>>> g.accidentalByStep('F')
<music21.pitch.Accidental sharp>
>>> g.accidentalByStep('G')
>>> f = key.KeySignature(-1)
>>> bbNote = note.Note('B-5')
>>> f.accidentalByStep(bbNote.step)
<music21.pitch.Accidental flat>

Fix a wrong note in F-major:

>>> wrongBNote = note.Note('B#4')
>>> if f.accidentalByStep(wrongBNote.step) != wrongBNote.pitch.accidental:
...    wrongBNote.pitch.accidental = f.accidentalByStep(wrongBNote.step)
>>> wrongBNote
<music21.note.Note B->

Set all notes to the correct notes for a key using the note’s Key Context. Before:

>>> s1 = stream.Stream()
>>> s1.append(key.KeySignature(4))  # E-major or C-sharp-minor
>>> s1.append(note.Note('C', type='half'))
>>> s1.append(note.Note('E-', type='half'))
>>> s1.append(key.KeySignature(-4))  # A-flat-major or F-minor
>>> s1.append(note.Note('A', type='whole'))
>>> s1.append(note.Note('F#', type='whole'))


>>> for n in s1.notes:
...    n.pitch.accidental = n.getContextByClass(key.KeySignature).accidentalByStep(n.step)
KeySignature.asKey(mode: Optional[str] = None, tonic: Optional[str] = None)

Return a key.Key object representing this KeySignature object as a key in the given mode or in the given tonic. If mode is None, and tonic is not provided, major is assumed. If both mode and tonic are provided, the tonic is ignored.

>>> ks = key.KeySignature(2)
>>> ks.asKey()
<music21.key.Key of D major>
>>> ks.asKey(mode='minor')
<music21.key.Key of b minor>

If mode is None, an attempt is made to solve for the mode:

>>> ks.asKey(tonic='A')
<music21.key.Key of A mixolydian>

But will raise KeyException if an impossible solution is requested:

>>> ks.asKey(tonic='D#')
Traceback (most recent call last):
music21.key.KeyException: Could not solve for mode from sharps=2, tonic=D#

Ionian and Aeolian are supplied instead of major or minor when deriving mode in this way:

>>> ks2 = key.KeySignature()
>>> ks2.asKey()
<music21.key.Key of C major>
>>> ks2.asKey(tonic='C')
<music21.key.Key of C ionian>

New in v7 – tonic argument to solve for mode.


Return a music21.scale.Scale object (or, actually, a subclass such as MajorScale or MinorScale) that is representative of this key signature and mode.

Raises KeySignatureException if mode is not in [None, ‘major’, ‘minor’].

>>> ks = key.KeySignature(3)
>>> ks
<music21.key.KeySignature of 3 sharps>
>>> ks.getScale('major')
<music21.scale.MajorScale A major>
>>> ks.getScale('minor')
<music21.scale.MinorScale F# minor>
KeySignature.transpose(value, *, inPlace=False)

Transpose the KeySignature by the user-provided value. If the value is an integer, the transposition is treated in half steps. If the value is a string, any Interval string specification can be provided. Alternatively, a music21.interval.Interval object can be supplied.

>>> a = key.KeySignature(2)
>>> a
<music21.key.KeySignature of 2 sharps>
>>> a.asKey('major')
<music21.key.Key of D major>
>>> b = a.transpose('p5')
>>> b
<music21.key.KeySignature of 3 sharps>
>>> b.asKey('major')
<music21.key.Key of A major>
>>> b.sharps
>>> c = b.transpose('-m2')
>>> c.asKey('major')
<music21.key.Key of G# major>
>>> c.sharps
>>> d = c.transpose('-a3')
>>> d.asKey('major')
<music21.key.Key of E- major>
>>> d.sharps

Transposition by semitone (or other chromatic interval)

>>> c = key.KeySignature(0)
>>> dFlat = c.transpose(1)
>>> dFlat
<music21.key.KeySignature of 5 flats>
>>> d = dFlat.transpose(1)
>>> d
<music21.key.KeySignature of 2 sharps>
>>> eFlat = d.transpose(1)
>>> eFlat
<music21.key.KeySignature of 3 flats>
KeySignature.transposePitchFromC(p: music21.pitch.Pitch, *, inPlace=False) Optional[music21.pitch.Pitch]

Takes a pitch in C major and transposes it so that it has the same step position in the current key signature.

Example: B is the leading tone in C major, so given a key signature of 3 flats, get the leading tone in E-flat major:

>>> ks = key.KeySignature(-3)
>>> p1 = pitch.Pitch('B')
>>> p2 = ks.transposePitchFromC(p1)

Original pitch is unchanged:

>>> ks2 = key.KeySignature(2)
>>> p2 = ks2.transposePitchFromC(p1)

For out of scale pitches the relationship still works; note also that original octave is preserved.

>>> p3 = pitch.Pitch('G-4')
>>> p4 = ks.transposePitchFromC(p3)
>>> p4.nameWithOctave

If inPlace is True then nothing is returned and the original pitch is modified.

>>> p5 = pitch.Pitch('C5')
>>> ks.transposePitchFromC(p5, inPlace=True)
>>> p5.nameWithOctave

New method in v6.

Methods inherited from Music21Object:

Methods inherited from ProtoM21Object:

KeySignature instance variables

Instance variables inherited from Music21Object:


class music21.key.Key(tonic: Union[str, music21.pitch.Pitch, music21.note.Note] = 'C', mode=None)

Note that a key is a sort of hypothetical/conceptual object. It probably has a scale (or scales) associated with it and a KeySignature, but not necessarily.

A Key object has all the attributes of a KeySignature and all the attributes of a DiatonicScale.

>>> cm = key.Key('c')  # lowercase = c minor.
>>> cm
<music21.key.Key of c minor>
>>> cm.mode
>>> cm.tonic
<music21.pitch.Pitch C>
>>> cm.sharps
>>> cm.pitchFromDegree(3)
<music21.pitch.Pitch E-4>
>>> cm.pitchFromDegree(7)
<music21.pitch.Pitch B-4>
>>> cSharpMaj = key.Key('C#')  # uppercase = C# major
>>> cSharpMaj
<music21.key.Key of C# major>
>>> cSharpMaj.sharps
>>> fFlatMaj = key.Key('F-')
>>> fFlatMaj
<music21.key.Key of F- major>
>>> fFlatMaj.sharps
>>> fFlatMaj.accidentalByStep('B')
<music21.pitch.Accidental double-flat>
>>> eDor = key.Key('E', 'dorian')
>>> eDor
<music21.key.Key of E dorian>
>>> eDor.sharps
>>> eDor.pitches
[<music21.pitch.Pitch E4>,
 <music21.pitch.Pitch F#4>,
 <music21.pitch.Pitch G4>,
 <music21.pitch.Pitch A4>,
 <music21.pitch.Pitch B4>,
 <music21.pitch.Pitch C#5>,
 <music21.pitch.Pitch D5>,
 <music21.pitch.Pitch E5>]

Key bases

Key read-only properties


if the Key is major or minor, return the parallel minor or major.

Otherwise, just returns self – this is the best way to not have random crashes in the middle of large datasets.

>>> k = key.Key('D')
>>> k
<music21.key.Key of D major>
>>> k.parallel
<music21.key.Key of d minor>
>>> k.parallel.parallel
<music21.key.Key of D major>
>>> key.Key('D', 'dorian').parallel
<music21.key.Key of D dorian>

if the Key is major or minor, return the relative minor or major.

Otherwise, just returns self – this is the best way to not have random crashes in the middle of large datasets.

Note that this uses .sharps as a speedup, so if that has been changed, there will be a problem…

>>> k = key.Key('E-')
>>> k
<music21.key.Key of E- major>
>>> k.relative
<music21.key.Key of c minor>
>>> k.relative.relative
<music21.key.Key of E- major>
>>> key.Key('D', 'dorian').relative
<music21.key.Key of D dorian>

Return the pitch name as a string with the proper case (upper = major; lower = minor)

Useful, but simple:

>>> k = key.Key('c#')
>>> k.tonicPitchNameWithCase
>>> k = key.Key('B')
>>> k.tonicPitchNameWithCase
>>> k.mode = 'minor'
>>> k.tonicPitchNameWithCase

Anything else will return the default (capital)

>>> k.mode = 'dorian'
>>> k.tonicPitchNameWithCase

Read-only properties inherited from KeySignature:

Read-only properties inherited from ConcreteScale:

Read-only properties inherited from Music21Object:

Read-only properties inherited from ProtoM21Object:

Key read/write properties

Read/write properties inherited from KeySignature:

Read/write properties inherited from ConcreteScale:

Read/write properties inherited from Music21Object:

Key methods


two Keys are equal if their tonics are equal and their modes are equal

Key.deriveByDegree(degree, pitchRef)

Given a degree and pitchReference derive a new Key object that has the same mode but a different tonic

Example: What minor key has scale degree 3 as B-flat?

>>> minorKey = key.Key(mode='minor')
>>> newMinor = minorKey.deriveByDegree(3, 'B-')
>>> newMinor
<music21.key.Key of g minor>

Note that in minor, the natural form is used:

>>> minorKey.deriveByDegree(7, 'E')
<music21.key.Key of f# minor>
>>> minorKey.deriveByDegree(6, 'G')
<music21.key.Key of b minor>

To use the harmonic form, change .abstract on the key to another abstract scale:

>>> minorKey.abstract = scale.AbstractHarmonicMinorScale()
>>> minorKey.deriveByDegree(7, 'E')
<music21.key.Key of f minor>
>>> minorKey.deriveByDegree(6, 'G')
<music21.key.Key of b minor>

Currently because of a limitation in bidirectional scale searching, melodic minor scales cannot be used as abstracts for deriving by degree.

New in v.6 – preserve mode in key.Key.deriveByDegree

Key.tonalCertainty(method='correlationCoefficient', *args, **keywords)

Provide a measure of tonal ambiguity for Key determined with one of many methods.

The correlationCoefficient assumes that the alternateInterpretations list has been filled from the use of a KeyWeightKeyAnalysis subclass.

>>> littlePiece = converter.parse("tinyNotation: 4/4 c4 d e f g a b c' e' g' e' c'")
>>> k = littlePiece.analyze('key')
>>> k
<music21.key.Key of C major>
>>> k.tonalCertainty()

Three most likely alternateInterpretations:

>>> k.alternateInterpretations[0:3]
[<music21.key.Key of a minor>, <music21.key.Key of F major>, <music21.key.Key of d minor>]
>>> k.correlationCoefficient
>>> k.alternateInterpretations[0].correlationCoefficient

least likely interpretation:

>>> k.alternateInterpretations[-1]
<music21.key.Key of F# major>

Note that this method only exists if the key has come from an analysis method. Otherwise it raises a KeySignatureException

>>> k2 = key.Key('b-')
>>> k2.tonalCertainty()
Traceback (most recent call last):
music21.key.KeySignatureException: cannot process ambiguity without a
    list of .alternateInterpretations
>>> k2.alternateInterpretations
Key.transpose(value, *, inPlace=False)

Transpose the Key by the user-provided value. If the value is an integer, the transposition is treated in half steps. If the value is a string, any Interval string specification can be provided. Alternatively, a music21.interval.Interval object can be supplied.

>>> dMajor = key.Key('D')
>>> dMajor
<music21.key.Key of D major>
>>> aMaj = dMajor.transpose('p5')
>>> aMaj
<music21.key.Key of A major>
>>> aMaj.sharps
>>> aMaj.tonic
<music21.pitch.Pitch A>
>>> aMaj.mode

inPlace works here

>>> changingKey = key.Key('g')
>>> changingKey
<music21.key.Key of g minor>
>>> changingKey.sharps
>>> changingKey.transpose('m-3', inPlace=True)
>>> changingKey
<music21.key.Key of e minor>
>>> changingKey.sharps
>>> changingKey.transpose(1, inPlace=True)
>>> changingKey
<music21.key.Key of f minor>
>>> changingKey.sharps
>>> changingKey.transpose(1, inPlace=True)
>>> changingKey
<music21.key.Key of f# minor>
>>> changingKey.transpose(1, inPlace=True)
>>> changingKey
<music21.key.Key of g minor>
>>> changingKey.transpose(1, inPlace=True)
>>> changingKey
<music21.key.Key of g# minor>

Methods inherited from KeySignature:

Methods inherited from DiatonicScale:

Methods inherited from ConcreteScale:

Methods inherited from Scale:

Methods inherited from Music21Object:

Methods inherited from ProtoM21Object:

Key instance variables

Instance variables inherited from Music21Object:



Utility function to change strings in the form of “Eb” to “E-” (for E-flat major) and leaves alone proper music21 strings (like “E-” or “f#”). A little bit complex because of parsing bb as B-flat minor and Bb as B-flat major.

>>> key.convertKeyStringToMusic21KeyString('Eb')
>>> key.convertKeyStringToMusic21KeyString('f#')
>>> key.convertKeyStringToMusic21KeyString('bb')
>>> key.convertKeyStringToMusic21KeyString('Bb')
>>> key.convertKeyStringToMusic21KeyString('b#')
>>> key.convertKeyStringToMusic21KeyString('c')
music21.key.pitchToSharps(value, mode=None)

Given a pitch or music21.pitch.Pitch object, return the number of sharps found in that mode.

The mode parameter can be ‘major’, ‘minor’, or most of the common church/jazz modes (‘dorian’, ‘mixolydian’, etc.) including Locrian.

If mode is omitted or not found, the default mode is major.

(extra points to anyone who can find the earliest reference to the Locrian mode in print. David Cohen and I (MSC) have been looking for this for years).

>>> key.pitchToSharps('c')
>>> key.pitchToSharps('c', 'minor')
>>> key.pitchToSharps('a', 'minor')
>>> key.pitchToSharps('d')
>>> key.pitchToSharps('e-')
>>> key.pitchToSharps('a')
>>> key.pitchToSharps('e', 'minor')
>>> key.pitchToSharps('f#', 'major')
>>> key.pitchToSharps('g-', 'major')
>>> key.pitchToSharps('c#')
>>> key.pitchToSharps('g#')
>>> key.pitchToSharps('e', 'dorian')
>>> key.pitchToSharps('d', 'dorian')
>>> key.pitchToSharps('g', 'mixolydian')
>>> key.pitchToSharps('e-', 'lydian')
>>> key.pitchToSharps('e-', 'lydian')
>>> key.pitchToSharps('a', 'phrygian')
>>> key.pitchToSharps('e', 'phrygian')
>>> key.pitchToSharps('f#')
>>> key.pitchToSharps('f-')
>>> key.pitchToSharps('f--')
>>> key.pitchToSharps('f--', 'locrian')
>>> key.pitchToSharps('a', 'ionian')
>>> key.pitchToSharps('a', 'aeolian')

But quarter tones don’t work:

>>> key.pitchToSharps('C~')
Traceback (most recent call last):
music21.key.KeyException: Cannot determine sharps for quarter-tone keys! silly!

Given a positive/negative number of sharps, return a Pitch object set to the appropriate major key value.

>>> key.sharpsToPitch(1)
<music21.pitch.Pitch G>
>>> key.sharpsToPitch(2)
<music21.pitch.Pitch D>
>>> key.sharpsToPitch(-2)
<music21.pitch.Pitch B->
>>> key.sharpsToPitch(-6)
<music21.pitch.Pitch G->

Note that these are music21.pitch.Pitch objects not just names:

>>> k1 = key.sharpsToPitch(6)
>>> k1
<music21.pitch.Pitch F#>
>>> k1.step
>>> k1.accidental
<music21.pitch.Accidental sharp>