music21.common¶

Utility constants, dictionaries, functions, and objects used throughout music21.

music21.common.fromRoman(num)

Convert a Roman numeral (upper or lower) to an int

http://code.activestate.com/recipes/81611-roman-numerals/

```>>> from music21 import *
>>> common.fromRoman('ii')
2
>>> common.fromRoman('vii')
7
```

Works with both IIII and IV forms: >>> common.fromRoman(‘MCCCCLXXXIX’) 1489 >>> common.fromRoman(‘MCDLXXXIX’) 1489

Some people consider this an error, but you see it in medieval documents:

```>>> common.fromRoman('ic')
99
```

But things like this are never seen, and thus cause an error:

```>>> common.fromRoman('vx')
Traceback (most recent call last):
Music21CommonException: input contains an invalid subtraction element: vx
```
music21.common.toRoman(num)

Convert a number from 1 to 3999 to a roman numeral

```>>> from music21 import *
>>> common.toRoman(2)
'II'
>>> common.toRoman(7)
'VII'
>>> common.toRoman(1999)
'MCMXCIX'
⁠
>>> common.toRoman("hi")
Traceback (most recent call last):
TypeError: expected integer, got <type 'str'>
```
music21.common.almostEqual(x, y=0.0, grain=1e-07)

The following four routines work for comparisons between floats that are normally inconsistent.

almostEquals(x, y) – returns True if x and y are within 0.0000001 of each other

```>>> from music21 import common
>>> common.almostEquals(1.000000001, 1)
True
>>> common.almostEquals(1.001, 1)
False
>>> common.almostEquals(1.001, 1, grain=0.1)
True
```
music21.common.almostEquals(x, y=0.0, grain=1e-07)

The following four routines work for comparisons between floats that are normally inconsistent.

almostEquals(x, y) – returns True if x and y are within 0.0000001 of each other

```>>> from music21 import common
>>> common.almostEquals(1.000000001, 1)
True
>>> common.almostEquals(1.001, 1)
False
>>> common.almostEquals(1.001, 1, grain=0.1)
True
```
music21.common.approximateGCD(values, grain=0.0001)

Given a list of values, find the lowest common divisor of floating point values.

```>>> from music21 import *
>>> common.approximateGCD([2.5,10, .25])
0.25
>>> common.approximateGCD([2.5,10])
2.5
>>> common.approximateGCD([2,10])
2.0
>>> common.approximateGCD([1.5, 5, 2, 7])
0.5
>>> common.approximateGCD([2,5,10])
1.0
>>> common.approximateGCD([2,5,10,.25])
0.25
>>> str(common.approximateGCD([1/3.,2/3.]))
'0.333333333333'
>>> str(common.approximateGCD([5/3.,2/3.,4]))
'0.333333333333'
>>> str(common.approximateGCD([5/3.,2/3.,5]))
'0.333333333333'
>>> str(common.approximateGCD([5/3.,2/3.,5/6.,3/6.]))
'0.166666666667'
```
music21.common.basicallyEqual(a, b)

returns true if a and b are equal except for whitespace differences

```>>> from music21 import *
>>> a = " hello there "
>>> b = "hello there"
>>> c = " bye there "
>>> common.basicallyEqual(a,b)
True
>>> common.basicallyEqual(a,c)
False
```
music21.common.basicallyEquals(a, b)

returns true if a and b are equal except for whitespace differences

```>>> from music21 import *
>>> a = " hello there "
>>> b = "hello there"
>>> c = " bye there "
>>> common.basicallyEqual(a,b)
True
>>> common.basicallyEqual(a,c)
False
```
music21.common.classToClassStr(classObj)

Convert a class object to a class string.

```>>> from music21 import *
>>> common.classToClassStr(note.Note)
'Note'
>>> common.classToClassStr(chord.Chord)
'Chord'
```
music21.common.cleanupFloat(floatNum, maxDenominator=1000)

Cleans up a floating point number by converting it to a fractions.Fraction object limited to a denominator of maxDenominator

```>>> from music21 import *
>>> common.cleanupFloat(0.33333327824)
0.333333333333...
⁠
>>> common.cleanupFloat(0.142857)
0.1428571428571...
```
```>>> common.cleanupFloat(1.5)
1.5
```
music21.common.decimalToTuplet(decNum)

For simple decimals (usually > 1), a quick way to figure out the fraction in lowest terms that gives a valid tuplet.

No it does not work really fast. No it does not return tuplets with denominators over 100. Too bad, math geeks. This is real life. :-)

returns (numerator, denominator)

```>>> from music21 import *
>>> common.decimalToTuplet(1.5)
(3, 2)
>>> common.decimalToTuplet(1.25)
(5, 4)
```

If decNum is < 1, the denominator will be greater than the numerator:

```>>> common.decimalToTuplet(.8)
(4, 5)
```

If decNum is <= 0, returns a ZeroDivisionError:

```>>> common.decimalToTuplet(-.02)
Traceback (most recent call last):
ZeroDivisionError: number must be greater than zero
```

Given an object, return three lists of names: methods, attributes, and properties.

Note that if a name/attribute is dynamically created by a property it cannot be found until that attribute is created.

TODO: this cannot properly partiton properties from methods

music21.common.dotMultiplier(dots)

dotMultiplier(dots) returns how long to multiply the note length of a note in order to get the note length with n dots

```>>> from music21 import *
>>> common.dotMultiplier(1)
1.5
>>> common.dotMultiplier(2)
1.75
>>> common.dotMultiplier(3)
1.875
```
music21.common.euclidGCD(a, b)

use Euclid’s algorithm to find the GCD of a and b

```>>> from music21 import *
>>> common.euclidGCD(2,4)
2
>>> common.euclidGCD(20,8)
4
>>> common.euclidGCD(20,16)
4
```
music21.common.findFormat(fmt)

Given a format defined either by a format name or an extension, return the format name as well as the output exensions.

Note that .mxl and .mx are only considered MusicXML input formats.

```>>> from music21 import *
>>> common.findFormat('mx')
('musicxml', '.xml')
>>> common.findFormat('.mxl')
('musicxml', '.xml')
>>> common.findFormat('musicxml')
('musicxml', '.xml')
>>> common.findFormat('jpeg')
('jpeg', '.jpg')
>>> common.findFormat('lily')
('lilypond', '.ly')
>>> common.findFormat('jpeg')
('jpeg', '.jpg')
>>> common.findFormat('humdrum')
('humdrum', '.krn')
>>> common.findFormat('txt')
('text', '.txt')
>>> common.findFormat('textline')
('textline', '.txt')
>>> common.findFormat('midi')
('midi', '.mid')
>>> common.findFormat('abc')
('abc', '.abc')
>>> common.findFormat('scl')
('scala', '.scl')
>>> common.findFormat('braille')
('braille', '.txt')
>>> common.findFormat('vexflow')
('vexflow', '.html')
>>> common.findFormat('capx')
('capella', '.capx')
```

Works the same whether you have a leading dot or not:

```>>> common.findFormat('md')
('musedata', '.md')
>>> common.findFormat('.md')
('musedata', '.md')
```

If you give something we can’t deal with, returns a Tuple of None, None:

```>>> common.findFormat('wpd')
(None, None)
```
music21.common.findFormatExtFile(fp)

Given a file path (relative or absolute) find format and extension used (not the output extension)

```>>> from music21 import *
>>> common.findFormatExtFile('test.mx')
('musicxml', '.mx')
>>> common.findFormatExtFile('long/file/path/test-2009.03.02.xml')
('musicxml', '.xml')
>>> common.findFormatExtFile('long/file/path.intermediate.png/test-2009.03.xml')
('musicxml', '.xml')
⁠
>>> common.findFormatExtFile('test.mus')
('finale', '.mus')
```
```>>> common.findFormatExtFile('test')
(None, None)
```

Windows drive + pickle >>> common.findFormatExtFile(‘d:/long/file/path/test.p’) (‘pickle’, ‘.p’)

On a windows networked filesystem

```>>> common.findFormatExtFile('\\long\file\path\test.krn')
('humdrum', '.krn')
```
music21.common.findFormatExtURL(url)

Given a URL, attempt to find the extension. This may scrub arguments in a URL, or simply look at the last characters.

```>>> from music21 import *
>>> urlA = 'http://kern.ccarh.org/cgi-bin/ksdata?l=cc/schubert/piano/d0576&file=d0576-06.krn&f=xml'
>>> urlB = 'http://kern.ccarh.org/cgi-bin/ksdata?l=cc/schubert/piano/d0576&file=d0576-06.krn&f=kern'
>>> urlC = 'http://kern.ccarh.org/cgi-bin/ksdata?l=cc/bach/cello&file=bwv1007-01.krn&f=xml'
>>> urlD = 'http://static.wikifonia.org/4918/musicxml.mxl'
>>> urlE = 'http://static.wikifonia.org/4306/musicxml.mxl'
>>> urlF = 'http://junk'
⁠
>>> common.findFormatExtURL(urlA)
('musicxml', '.xml')
>>> common.findFormatExtURL(urlB)
('humdrum', '.krn')
>>> common.findFormatExtURL(urlC)
('musicxml', '.xml')
>>> common.findFormatExtURL(urlD)
('musicxml', '.mxl')
>>> common.findFormatExtURL(urlE)
('musicxml', '.mxl')
>>> common.findFormatExtURL(urlF)
(None, None)
```
music21.common.findFormatFile(fp)

Given a file path (relative or absolute) return the format

```>>> from music21 import *
>>> common.findFormatFile('test.xml')
'musicxml'
>>> common.findFormatFile('long/file/path/test-2009.03.02.xml')
'musicxml'
>>> common.findFormatFile('long/file/path.intermediate.png/test-2009.03.xml')
'musicxml'
```

Windows drive + pickle >>> common.findFormatFile(‘d:/long/file/path/test.p’) ‘pickle’

On a windows networked filesystem

```>>> common.findFormatFile('\\long\file\path\test.krn')
'humdrum'
```
music21.common.findInputExtension(fmt)

Given an input format, find and return all possible input extensions.

```>>> from music21 import *
>>> a = common.findInputExtension('musicxml')
>>> a
['.xml', '.mxl', '.mx']
>>> a = common.findInputExtension('mx')
>>> a
['.xml', '.mxl', '.mx']
>>> a = common.findInputExtension('humdrum')
>>> a
['.krn']
>>> common.findInputExtension('musedata')
['.md', '.musedata', '.zip']
```
music21.common.findWeakRef(target)

Given an object or composition of objects, find an attribute that is a weakref. This is a diagnostic tool.

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

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

```>>> from music21 import *
>>> a = common.formatStr('test', '1', 2, 3)
>>> print a
test 1 2 3
```
music21.common.getBuildDocFilePath()

Return the directory that contains the documentation RST files.

music21.common.getBuildDocRstFilePath()

Return the directory that contains the documentation RST files.

music21.common.getCorpusContentDirs()

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

```>>> from music21 import *
>>> fp = common.getCorpusContentDirs()
>>> fp # this test will be fragile, depending on composition of dirs
['airdsAirs', 'bach', 'beethoven', 'ciconia', 'corelli', 'cpebach', 'demos', 'essenFolksong', 'handel', 'haydn',
'schoenberg', 'schumann', 'schumann_clara', 'theoryExercises', 'trecento', 'verdi']
```
music21.common.getCorpusFilePath()

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

```>>> from music21 import *
>>> fp = common.getCorpusFilePath()
>>> fp.endswith('music21/corpus') or fp.endswith(r'music21\corpus')
True
```
music21.common.getMd5(value=None)

Return a string from an md5 haslib

```>>> from music21 import *
>>> common.getMd5('test')
```

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

```>>> from music21 import *
True
```
music21.common.getMissingImportStr(modNameList)

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.

```>>> from music21 import *
>>> common.getMissingImportStr(['matplotlib'])
'Certain music21 functions might need the optional package matplotlib; if you run into errors, install it by following the instructions at http://mit.edu/music21/doc/html/installAdditional.html'
>>> common.getMissingImportStr(['matplotlib', 'numpy'])
'Certain music21 functions might need these optional packages: matplotlib, numpy; if you run into errors, install it by following the instructions at http://mit.edu/music21/doc/html/installAdditional.html'
```
music21.common.getNumFromStr(usrStr, numbers='0123456789')

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

```>>> from music21 import *
>>> common.getNumFromStr('23a')
('23', 'a')
>>> common.getNumFromStr('23a954sdfwer')
('23954', 'asdfwer')
>>> common.getNumFromStr('')
('', '')
```
music21.common.getPackageData()

Return a list of package data in the format specified by setup.py. 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 setup.py.

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 __init__.py files are colllected.

music21.common.getPlatform()

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).

music21.common.getSourceFilePath()

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

music21.common.greaterThan(x, y=0.0, grain=1e-07)

greaterThan returns True if x is greater than and not almostEquals y

```>>> from music21 import *
>>> common.greaterThan(5, 4)
True
>>> common.greaterThan(5.05, 5.02)
True
>>> common.greaterThan(5.000000000005, 5.000000000006)
False
>>> common.greaterThan(5.000000000006, 5.000000000005)
False
```
music21.common.greaterThanOrEqual(x, y=0.0, grain=1e-07)

greaterThan returns True if x is greater than or almostEquals y

music21.common.groupContiguousIntegers(src)

Given a list of integers, group contiguous values into sub lists

```>>> from music21 import *
>>> common.groupContiguousIntegers([3, 5, 6])
[[3], [5, 6]]
>>> common.groupContiguousIntegers([3, 4, 6])
[[3, 4], [6]]
>>> common.groupContiguousIntegers([3, 4, 6, 7])
[[3, 4], [6, 7]]
>>> common.groupContiguousIntegers([3, 4, 6, 7, 20])
[[3, 4], [6, 7], [20]]
>>> common.groupContiguousIntegers([3, 4, 5, 6, 7])
[[3, 4, 5, 6, 7]]
>>> common.groupContiguousIntegers([3])
[[3]]
>>> common.groupContiguousIntegers([3, 200])
[[3], [200]]
```
music21.common.isIterable(usrData)

Returns True if is the object can be iter’d over

```>>> from music21 import *
>>> common.isIterable([5, 10])
True
>>> common.isIterable('sharp')
False
>>> common.isIterable((None, None))
True
>>> common.isIterable(stream.Stream())
True
```
music21.common.isListLike(usrData)

Returns True if is a List or a Set or a Tuple

```>>> from music21 import *
>>> common.isListLike([])
True
>>> common.isListLike('sharp')
False
>>> common.isListLike((None, None))
True
>>> common.isListLike(stream.Stream())
False
```
music21.common.isNum(usrData)

check if usrData is a number (float, int, long, Decimal), return boolean IMPROVE: when 2.6 is everywhere: add numbers class.

```>>> from music21 import *
>>> common.isNum(3.0)
True
>>> common.isNum(3)
True
>>> common.isNum('three')
False
```
music21.common.isPowerOfTwo(n)

returns True if argument is either a power of 2 or a reciprocal of a power of 2. Uses almostEquals so that a float whose reminder after taking a log is nearly zero is still True

```>>> from music21 import *
>>> common.isPowerOfTwo(3)
False
>>> common.isPowerOfTwo(18)
False
>>> common.isPowerOfTwo(1024)
True
>>> common.isPowerOfTwo(1024.01)
False
>>> common.isPowerOfTwo(1024.00001)
True
```
music21.common.isStr(usrData)

Check of usrData is some form of string, including unicode.

```>>> from music21 import *
>>> common.isStr(3)
False
>>> common.isStr('sharp')
True
>>> common.isStr(u'flat')
True
```
music21.common.isWeakref(referent)

Test if an object is a weakref

```>>> from music21 import *
>>> class Mock(object):
...     pass
>>> a1 = Mock()
>>> a2 = Mock()
>>> common.isWeakref(a1)
False
>>> common.isWeakref(3)
False
>>> common.isWeakref(common.wrapWeakref(a1))
True
```
music21.common.lcm(filterList)

Find the least common multiple of a list of values

```>>> from music21 import *
>>> common.lcm([3,4,5])
60
>>> common.lcm([3,4])
12
>>> common.lcm([1,2])
2
>>> common.lcm([3,6])
6
```
music21.common.lessThan(x, y=0.0, grain=1e-07)

lessThan – returns True if x is less than and not almostEquals y

```>>> from music21 import *
>>> common.lessThan(5, 4)
False
>>> common.lessThan(5.2, 5.5)
True
>>> common.lessThan(5.2, 5.5, grain=1)
False
>>> common.lessThan(5.000000000005, 5.000000000006)
False
>>> common.lessThan(5.000000000006, 5.000000000005)
False
```
music21.common.lessThanOrEqual(x, y=0.0, grain=1e-07)

lessThan – returns True if x is less than and not almostEquals y

```>>> from music21 import *
>>> common.lessThanOrEqual(4, 4)
True
>>> common.lessThanOrEqual(5.2, 5.5)
True
>>> common.lessThanOrEqual(5.2, 5.5)
True
>>> common.lessThanOrEqual(5.000000000005, 5.000000000006)
True
```
music21.common.nearestCommonFraction(x, grain=0.01)

Given a value that suggests a floating point fraction, like .33, return a float that provides greater specification, such as .333333333

```>>> from music21 import *
>>> common.nearestCommonFraction(.333) == 1/3.
True
>>> common.nearestCommonFraction(.33) == 1/3.
True
>>> common.nearestCommonFraction(.35) == 1/3.
False
>>> common.nearestCommonFraction(.2) == .2
True
>>> common.nearestCommonFraction(.125)
0.125
```
music21.common.nearestMultiple(n, unit)

Given a positive value n, return the nearest multiple of the supplied unit as well as the difference (error) to seven significant digits.

```>>> from music21 import *
>>> print common.nearestMultiple(.25, .25)
(0.25, 0.0)
>>> print common.nearestMultiple(.35, .25)
(0.25, 0.1...)
```

Note that this one also has an error of .1 but it’s a positive error off of 0.5 >>> print common.nearestMultiple(.4, .25) (0.5, 0.1...)

```>>> common.nearestMultiple(.4, .25)[0]
0.5
>>> common.nearestMultiple(23404.001, .125)[0]
23404.0
>>> common.nearestMultiple(23404.134, .125)[0]
23404.125
>>> common.nearestMultiple(.001, .125)[0]
0.0
⁠
>>> common.almostEquals(common.nearestMultiple(.25, (1/3.))[0], .33333333)
True
>>> common.almostEquals(common.nearestMultiple(.55, (1/3.))[0], .66666666)
True
>>> common.almostEquals(common.nearestMultiple(234.69, (1/3.))[0], 234.6666666)
True
>>> common.almostEquals(common.nearestMultiple(18.123, (1/6.))[0], 18.16666666)
True
```
music21.common.normalizeFilename(name)

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 normal string.

```>>> from music21 import *
>>> common.normalizeFilename(u'03-Niccolò all\'lessandra.not really.xml')
'03-Niccolo_all_lessandra_not_really.xml'
```
music21.common.numToIntOrFloat(value)

Given a number, return an integer if it is very close to an integer, otherwise, return a float.

```>>> from music21 import *
>>> common.numToIntOrFloat(1.0)
1
>>> common.numToIntOrFloat(1.00003)
1.00003
>>> common.numToIntOrFloat(1.5)
1.5
>>> common.numToIntOrFloat(1.0000000005)
1
```
music21.common.ordinalAbbreviation(value, plural=False)

Return the ordinal abbreviations for integers

```>>> from music21 import common
>>> common.ordinalAbbreviation(3)
'rd'
>>> common.ordinalAbbreviation(255)
'th'
>>> common.ordinalAbbreviation(255, plural=True)
'ths'
```
music21.common.pitchList(pitchList)

utility method that replicates the previous behavior of lists of pitches

music21.common.roundToHalfInteger(num)

Given a floating-point number, round to the nearest half-integer.

```>>> from music21 import *
>>> common.roundToHalfInteger(1.2)
1
>>> common.roundToHalfInteger(1.35)
1.5
>>> common.roundToHalfInteger(1.8)
2
>>> common.roundToHalfInteger(1.6234)
1.5
```
music21.common.sortFilesRecent(fileList)

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

```>>> from music21 import *
>>> import os
>>> a = os.listdir(os.curdir)
>>> b = common.sortFilesRecent(a)
```
music21.common.sortModules(moduleList)

Sort a lost of imported module names such that most recently modified is first

music21.common.spaceCamelCase(usrStr, replaceUnderscore=True)

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 _)

```>>> from music21 import *
>>> 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'
⁠
>>> common.spaceCamelCase('hello_myke')
'hello myke'
>>> common.spaceCamelCase('hello_myke', replaceUnderscore = False)
'hello_myke'
```
music21.common.standardDeviation(coll, bassel=False)

Given a collection of values, return the standard deviation.

```>>> from music21 import *
>>> common.standardDeviation([2,4,4,4,5,5,7,9])
2.0
>>> common.standardDeviation([600, 470, 170, 430, 300])
147.3227...
>>> common.standardDeviation([4, 2, 5, 8, 6], bassel=True)
2.23606...
```
music21.common.stripAccents(inputString)

removes accents from unicode strings.

```>>> from music21 import *
>>> s = u'tr\u00e8s vite'
>>> u'\u00e8' in s
True
>>> common.stripAccents(s)
u'tres vite'
```

Function that changes all memory addresses in the given textString with (replacement). This is useful for testing that a function gives an expected result even if the result contains references to memory locations. So for instance:

```>>> from music21 import *
```

while this is left alone:

```>>> common.stripAddresses("{0.0} <music21.humdrum.MiscTandem *>I humdrum control>")
'{0.0} <music21.humdrum.MiscTandem *>I humdrum control>'
```
music21.common.toUnicode(usrStr)

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

```>>> from music21 import *
>>> common.toUnicode('test')
u'test'
>>> common.toUnicode(u'test')
u'test'
```
music21.common.unitBoundaryProportion(series)

Take a series of parts with an implied sum, and create unit-interval boundaries proportional to the series components.

```>>> from music21 import *
>>> common.unitBoundaryProportion([1,1,2])
[(0, 0.25), (0.25, 0.5), (0.5, 1.0)]
>>> common.unitBoundaryProportion([8,1,1])
[(0, 0.8...), (0.8..., 0.9...), (0.9..., 1.0)]
```
music21.common.unitNormalizeProportion(values)

Normalize values within the unit interval, where max is determined by the sum of the series.

```>>> from music21 import *
>>> common.unitNormalizeProportion([0,3,4])
[0.0, 0.42857142857142855, 0.5714285714285714]
>>> common.unitNormalizeProportion([1,1,1])
[0.3333333..., 0.333333..., 0.333333...]
```

On 32-bit computers this number is inexact. On 64-bit it works fine.

#>>> common.unitNormalizeProportion([.2, .6, .2]) #[0.20000000000000001, 0.59999999999999998, 0.20000000000000001]

music21.common.unwrapWeakref(referent)

Utility function that gets an object that might be an object itself or a weak reference to an object. It returns obj() if it’s a weakref and obj if it’s not.

```>>> from music21 import *
>>> class Mock(object):
...     pass
>>> a1 = Mock()
>>> a2 = Mock()
>>> a2.strong = a1
>>> a2.weak = common.wrapWeakref(a1)
>>> common.unwrapWeakref(a2.strong) is a1
True
>>> common.unwrapWeakref(a2.weak) is a1
True
>>> common.unwrapWeakref(a2.strong) is common.unwrapWeakref(a2.weak)
True
```
music21.common.weightedSelection(values, weights, randomGenerator=None)

Given a list of values and an equal-sized list of weights, return a randomly selected value using the weight.

Example: sum -1 and 1 for 100 values; should be around 0 or at least between -30 and 30

```>>> from music21 import *
>>> -30 < sum([common.weightedSelection([-1, 1], [1,1]) for x in range(100)]) < 30
True
```
music21.common.wrapWeakref(referent)

utility function that wraps objects as weakrefs but does not wrap already wrapped objects

DefaultHash¶

Inherits from: dict

class music21.common.DefaultHash(dictIn=None, default=None, callDefault=False)

A replacement for dictionaries that behave a bit more like perl hashes. No more KeyErrors. The difference between DefaultHash and defaultdict is that the Dict values come first in the definition and that default can be set to None (which it is) or to any object.

If you want a factory that makes hashes with a particular different default, use:

falsehash = lambda h = None: common.DefaultHash(h, default = False) a = falsehash({“A”: falsehash(), “B”: falsehash()}) print(a[“A”][“hi”]) # returns False

there’s probably a way to use this to create a data structure of arbitrary dimensionality, though it escapes this author.

if callDefault is True then the default is called:

common.DefaultHash(default = list, callDefault = True)

will create a new List for each element

DefaultHash attributes

Attributes without Documentation: default, callDefault

Attributes inherited from dict: fromkeys

DefaultHash methods

get(key, *args)

No documentation.

Methods inherited from dict: clear(), copy(), has_key(), items(), iteritems(), iterkeys(), itervalues(), keys(), pop(), popitem(), setdefault(), update(), values(), viewitems(), viewkeys(), viewvalues()

Iterator¶

class music21.common.Iterator(data)

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

Iterator methods

next()

No documentation.

SingletonCounter¶

class music21.common.SingletonCounter

A simple counter that can produce unique numbers regardless of how many instances exist.

Timer¶

class music21.common.Timer

An object for timing.

Timer methods

clear()

No documentation.

start()

Explicit start method; will clear previous values. Start always happens on initialization.

stop()

No documentation.

defList¶

Inherits from: list

class music21.common.defList(value=None, default=None, callDefault=False)

A replacement for lists that behave a bit more like perl arrays. No more ListErrors.

defList attributes

Attributes without Documentation: default, callDefault

defList methods

Methods inherited from list: append(), count(), extend(), index(), insert(), pop(), remove(), reverse(), sort()