Common is a collection of utility functions, objects, constants and dictionaries used throughout music21.

functions in common/ can import from music21.defaults, music21.exceptions21, and music21.ext and that is all (except in tests and doctests).

For historical reasons all the (non-private) functions etc. of the common/ folder are available by importing common.

split according to function – September 2015


music21.common.camelCaseToHyphen(usrStr, replacement='-')

Given a camel-cased string, or a mixture of numbers and characters, create a space separated string.

The replacement can be specified to be something besides a hyphen, but only a single character and not (for internal reasons) an uppercase character.

code from
>>> common.camelCaseToHyphen('movementName')
>>> common.camelCaseToHyphen('movementNameName')
>>> common.camelCaseToHyphen('fileName', replacement='_')

Some things you cannot do:

>>> common.camelCaseToHyphen('fileName', replacement='NotFound')
Traceback (most recent call last):
Exception: Replacement must be a single character.
>>> common.camelCaseToHyphen('fileName', replacement='A')
Traceback (most recent call last):
Exception: Replacement cannot be an uppercase character.

Useful for a temporary cd for use in a with statement:

with cd(‘/Library/’):

will switch temporarily, and then switch back when leaving.

music21.common.defaultDeepcopy(obj, memo, callInit=True)

Unfortunately, it is not possible to do something like:

def __deepcopy__(self, memo):
if self._noDeepcopy:
return self.__class__()
copy.deepcopy(self, memo, ignore__deepcopy__=True)

Or, else: return NotImplemented

so that’s what this is for:

def __deepcopy__(self, memo):
if self._noDeepcopy:
return self.__class__()
common.defaultDeepcopy(obj, memo)

looks through both __slots__ and __dict__ and does a deepcopy of anything in each of them and returns the new object.

If callInit is False, then only __new__() is called. This is much faster if you’re just going to overload every instance variable.

music21.common.formatStr(msg, *arguments, **keywords)

Format one or more data elements into string suitable for printing straight to stderr or other outputs

>>> a = common.formatStr('test', '1', 2, 3)
>>> print(a)
test 1 2 3

Get all dirs that are found in the corpus that contain content; that is, exclude dirs that have code or other resources.

>>> fp = common.getCorpusContentDirs()
>>> fp # this test will be fragile, depending on composition of dirs
['airdsAirs', 'bach', 'beethoven', 'ciconia', 'corelli', 'cpebach',
'demos', 'essenFolksong', 'handel', 'haydn', 'josquin', 'leadSheet',
'luca', 'miscFolk', 'monteverdi', 'mozart', 'oneills1850', 'palestrina',
'ryansMammoth', 'schoenberg', 'schumann', 'schumann_clara',
'theoryExercises', 'trecento', 'verdi', 'weber']

Make sure that all corpus data has a directoryInformation tag in CoreCorpus.

>>> cc = corpus.corpora.CoreCorpus()
>>> failed = []
>>> di = [d.directoryName for d in cc.directoryInformation]
>>> for f in fp:
...     if f not in di:
...         failed.append(f)
>>> failed

Get the stored music21 directory that contains the corpus metadata cache.

>>> fp = common.getCorpusFilePath()
>>> fp.endswith('music21/corpus') or fp.endswith(r'music21\corpus')

Return an md5 hash from a string. If no value is given then the current time plus a random number is encoded.

>>> common.getMd5('test')
Return type:str

Get the stored music21 directory that contains the corpus metadata cache.

>>> fp = common.getMetadataCacheFilePath()
>>> fp.endswith('corpus/_metadataCache') or fp.endswith(r'corpus\_metadataCache')
Return type:str

Given a list of missing module names, returns a nicely-formatted message to the user that gives instructions on how to expand music21 with optional packages.

>>> print(common.getMissingImportStr(['matplotlib']))
Certain music21 functions might need the optional package matplotlib;
if you run into errors, install it by following the instructions at
>>> print(common.getMissingImportStr(['matplotlib', 'numpy']))
Certain music21 functions might need these optional packages: matplotlib, numpy;
if you run into errors, install them by following the instructions at    
music21.common.getNumFromStr(usrStr, numbers='0123456789')

Given a string, extract any numbers. Return two strings, the numbers (as strings) and the remaining characters.

>>> common.getNumFromStr('23a')
('23', 'a')
>>> common.getNumFromStr('23a954sdfwer')
('23954', 'asdfwer')
>>> common.getNumFromStr('')
('', '')
Return type:tuple(str)

Return a list of package data in the format specified by This creates a very inclusive list of all data types.

music21.common.getPackageDir(fpMusic21=None, relative=True, remapSep='.', packageOnly=True)

Manually get all directories in the music21 package, including the top level directory. This is used in

If relative is True, relative paths will be returned.

If remapSep is set to anything other than None, the path separator will be replaced.

If packageOnly is true, only directories with files are collected.


Return the name of the platform, where platforms are divided between ‘win’ (for Windows), ‘darwin’ (for MacOS X), and ‘nix’ for (GNU/Linux and other variants).

Return type:str

Get the music21 directory that contains source files such as, etc.. This is not the same as the outermost package development directory.

Return type:str
music21.common.hyphenToCamelCase(usrStr, replacement='-')

given a hyphen-connected-string, change it to a camelCaseConnectedString.

The replacement can be specified to be something besides a hyphen.

code from

>>> common.hyphenToCamelCase('movement-name')
>>> common.hyphenToCamelCase('movement_name', replacement='_')

take a name that might contain unicode characters, punctuation, or spaces and normalize it so that it is POSIX compliant (except for the limit on length).

Takes in a string or unicode string and returns a string (unicode in Py3) without any accented characters.

>>> common.normalizeFilename(u'03-Niccolò all’lessandra.not really.xml')
Return type:str

utility method that replicates the previous behavior of lists of pitches

music21.common.readFileEncodingSafe(filePath, firstGuess='utf-8')

Slow, but will read a file of unknown encoding as safely as possible using the LGPL chardet package in music21.ext.

Let’s try to load this file as ascii – it has a copyright symbol at the top so it won’t load in Python3:

>>> import os 
>>> c = os.path.join(common.getSourceFilePath(), 'common', '')
>>> f = open(c)
>>> data =
Traceback (most recent call last):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position ...: 
    ordinal not in range(128)

That won’t do! now I know that it is in utf-8, but maybe you don’t. Or it could be an old humdrum or Noteworthy file with unknown encoding. This will load it safely.

>>> data = common.readFileEncodingSafe(c)
>>> data[0:30]
'#-*- coding: utf-8 -*-\n#------'

Well, that’s nothing, since the first guess here is utf-8 and it’s right. So let’s give a worse first guess:

>>> data = common.readFileEncodingSafe(c, firstGuess='SHIFT_JIS') # old Japanese standard
>>> data[0:30]
'#-*- coding: utf-8 -*-\n#------'

It worked!

Note that this is slow enough if it gets it wrong that the firstGuess should be set to something reasonable like ‘ascii’ or ‘utf-8’.

Return type:str
music21.common.relativepath(path, start=None)

A cross-platform wrapper for os.path.relpath(), which returns path if under Windows, otherwise returns the relative path of path.

This avoids problems under Windows when the current working directory is on a different drive letter from path.

Return type:str

return bool if we are running under iPython Notebook (not iPython)

(no tests, since will be different)

This post:


says not to do this, but really, I can’t think of another way to have different output as default.

Return type:bool

Given two files, sort by most recent. Return only the file paths.

>>> import os
>>> a = os.listdir(os.curdir)
>>> b = common.sortFilesRecent(a)
Return type:list(str)

Sort a lost of imported module names such that most recently modified is first. In ties, last accesstime is used then module name

Will return a different order each time depending on the last mod time

Return type:list(str)
music21.common.spaceCamelCase(usrStr, replaceUnderscore=True, fixMeList=None)

Given a camel-cased string, or a mixture of numbers and characters, create a space separated string.

If replaceUnderscore is True (default) then underscores also become spaces (but without the _)

>>> common.spaceCamelCase('thisIsATest')
'this Is A Test'
>>> common.spaceCamelCase('ThisIsATest')
'This Is A Test'
>>> common.spaceCamelCase('movement3')
'movement 3'
>>> common.spaceCamelCase('opus41no1')
'opus 41 no 1'
>>> common.spaceCamelCase('opus23402no219235')
'opus 23402 no 219235'
>>> common.spaceCamelCase('opus23402no219235').title()
'Opus 23402 No 219235'

There is a small list called fixMeList that can fix mistakes.

>>> common.spaceCamelCase('PMFC22')
'PMFC 22'
>>> common.spaceCamelCase('hello_myke')
'hello myke'
>>> common.spaceCamelCase('hello_myke', replaceUnderscore = False)
Return type:str

removes accents from unicode strings.

>>> s = u'trés vite'
>>> u'é' in s

This works on Python2, but the doctest does not.

>>> if ext.six.PY3:
...     common.stripAccents(s)
... else: 'tres vite'
'tres vite'

Convert this tring to a unicode string; if already a unicode string, do nothing.

>>> common.toUnicode('test')
>>> common.toUnicode(u'test')

Note: this method is NOT USED and could disappear without notice.

Return type:str


class music21.common.Iterator(data)

A simple Iterator object used to handle iteration of Streams and other list-like objects.

>>> i = common.Iterator([2,3,4])
>>> for x in i:
...     print(x)
>>> for y in i:
...     print(y)

Iterator methods


class music21.common.SingletonCounter

A simple counter that can produce unique numbers (in ascending order) regardless of how many instances exist.

Instantiate and then call it.

>>> sc = common.SingletonCounter()
>>> v0 = sc()
>>> v1 = sc()
>>> v1 > v0
>>> sc2 = common.SingletonCounter()
>>> v2 = sc2()
>>> v2 > v1


class music21.common.SlottedObject


Provides template for classes implementing slots allowing it to be pickled properly.

Only use SlottedObjects for objects that we expect to make so many of that memory storage and speed become an issue. Thus, unless you are Xenakis, Glissdata is probably not the best example:

>>> import pickle
>>> class Glissdata(common.SlottedObject):
...     __slots__ = ('time', 'frequency')
>>> s = Glissdata()
>>> s.time = 0.125
>>> s.frequency = 440.0
>>> out = pickle.dumps(s)
>>> t = pickle.loads(out)
>>> t.time, t.frequency
(0.125, 440.0)


TestMock read/write properties

TestMock methods


class music21.common.Timer

An object for timing. Call it to get the current time since starting.

>>> t = common.Timer()
>>> now = t()
>>> nownow = t()
>>> nownow > now

Call stop to stop it. Calling start again will reset the number

>>> t.stop()
>>> stopTime = t()
>>> stopNow = t()
>>> stopTime == stopNow

All this had better take less than one second!

>>> stopTime < 1

Timer methods


Explicit start method; will clear previous values.

Start always happens on initialization.



class music21.common.defaultlist(fx)

Call a function for every time something is missing:


>>> a = common.defaultlist(lambda:True)
>>> a[5]