Developer Guidelines¶
Music21
welcomes contributions such as bug reports, new features,
fixes, and documentation improvements. The project
repository is hosted at
GitHub.
Resources¶
Get to know this before contributing:
Project Scope¶
Contributions to music21
should fix bugs or add to coverage of
corner cases already part of the project and not add major new features
without discussion.
In the first few years of music21
, major new areas of investigation
(medieval rhythm encoding, contour analysis, etc.) were routinely added
to the system. Now features that are unlikely to be of general use are
encouraged to live in their own projects that import and extend
music21
.
It is easy to create your own project and have that import music21
–
over time the maintenance burden of “drive-by-feature-addition” has
become substantial.
Preparing to Contribute¶
Be sure to install all requirements in requirements_dev.txt
via:
pip3 install -r requirements_dev.txt
There are several tools needed for fully testing music21 that aren’t
included in the standard requirements.txt
.
Issue Tickets¶
Please use the provided templates for bug reports or feature proposals. For issues parsing file formats, (i.e. missing/buggy features not translated to or from that format), please add to (or start) a general ticket for all support requests for that format. (Some formats are no longer being actively maintained, such as MEI, LilyPond, and MuseData, but well-tested patches can be merged.)
Good bug reports clearly state the unexpected behavior and include a short set of commands to reproduce the issue. If your example requires loading a file, a two-measure file is appropriate; a symphony movement is not–that’s a support request. GitHub is not a support channel.
Speaking of support, helpful people hang out on the mailing list or Stack Overflow.
Submitting Pull Requests¶
Open an issue to propose a feature or report a bug before raising a pull request. You can include a diff or link to your own repo if you’ve already started some of the work. (Changes where the motivation is self-evident, like handling exceptions or increasing test coverage, don’t need issue tickets.)
If your PR fixes an existing issue, please use a GitHub keyword (“Fixes #NNNN”) in the body of the PR so that the issue will be closed on merge.
You can run locally the same tests that GitHub Actions will run. Install
pylint
and flake8
and run them against the files you edited, and
give the test suite a go, also. (Quick start: run
python3 -m music21.test.multiprocessTest
.) If you miss something and
GitHub Actions pesters you with red “X”s, just expand the details to get
the line-by-line violations, and push another commit.
Speaking of commits, use incremental commits with descriptive messages rather than force-pushing, which prevents the reviewer from assessing what changed between reviews. (Squashing commits will be handled by the merger.)
Note that new contributions are generally expected to increase the test coverage in coveralls.io – when you submit a PR, you’ll see a report of how much coverage has changed by your contributions. Look over the lines that are uncovered and make sure to write tests for them.
Style Guide¶
Music21
began in Perl. Now it interfaces with the TypeScript package
music21j
. Both of those languages use camelCase
extensively. For
these reasons, as well as for backward compatibility, we adhere to
camelCase
naming–rather than Python PEP8 snake_case
naming–for
public APIs such as method names, arguments, and the like.
That said, snake_case is acceptable in new contributions for internal variables that are not exposed publicly. Some screen readers can pronounce these names better and make them more accessible (however, more modern screen readers seem to do well with camelCase). However, all exposed methods and functions and their exposed arguments must be in camelCase.
Conventions:
Strings MUST be ‘single-quoted’, but “double quotes” are allowed internally
This rule applies to triple quotes and doc strings also, contrary to PEP 257.
Docstrings must begin and end on their own lines. No one-line doc-strings or text immediately following the triple quotes.
When there is a hyphen or single quote in the string, double quotes should be used, not escaping/backslashing.
For long streams of TinyNotation or Lilypond code, which both use single quotes to indicate octave, triple single quotes around the string are better than double quotes. Internal whitespace rarely matters in those formats.
Documentation should follow quoting in American English grammar when not discussing code. So for instance, a quotation in documentation is in double quotes.
Variable names:
Need to be unambiguous, even if rather long.
Must begin with lowercase (or underscore + lowercase) unless they represent classes.
snake_case is allowed for private variables.
camelCase is required for public.
Line lengths are capped at 100, but if approaching this limit, look for ways to avoid one-lining.
if it’s easy to split your line into two which are both under 80 characters, do so.
Line continuation characters (
\
) are not allowed; use open parentheses.Prefer f-strings to
.format()
. The%
interpolation is no longer allowed.Annotating types is required in new code, and encouraged to be added to older code.
e.g.
self.counter: int = 0
ordef makeNoises() -> list['noise.Noise']:
The typing library should always be imported as
t
.Use
type | None
rather thant.Optional[type]
.
Prefer enums to string configurations
In music21.common.enums, there is a StrEnum class for nearly-backwards compatible replacement of a former string argument with an enum.
New Enums do not need to inherit from StrEnum or IntEnum.
Enum members should be in ALL_CAPS with underscores, unless there is a good reason (such as case differentiation) to use CamelCase. I personally hate this convention–it looks like shouting–and will revisit it if
music21
is ever ported to a language where this is not the convention. Do not leave out underscores in the member names; it makes it hard for people whose native language is not English to parse and impossible for screen readers.
New classes should strongly endeavor to follow Liskov Substitution Principle.
Exceptions may be granted if the class structures follow names that are in common musical use but whose real world objects do not follow this principle. For instance, a
Manx
is a subclass ofCat
withoutself.tail
. Sometimes, however, rewriting the superclass might be possible (perhapsself.tail: t.Optional[Tail]
).Music21
was originally designed without this principle in mind, so you will find parts of the system that do not follow LSP and for backwards compatibility never will. I (Myke) have personally apologized to Barbara Liskov for my past ignorance.
Use Sphinx formatting to link to classes and methods in docstrings
Prefer methods that by default do not alter the object passed in and instead return a new one. It is permitted and encouraged to have an
inPlace: bool = False
argument that allows for manipulation of the original object. WheninPlace
is True, nothing should be returned (not true formusic21j
since passing through objects is so expected in JavaScript thanks to JQuery and other libraries). Use the@overload
decorator to show how this parameter affects the return value – Python makes this a bit hard, but see for instance,getElementsByClass()
for an example of how to use this.Use descriptive pull request titles (rather than GitHub’s default “Update pitch.py”)
Do not have a PR title so long that it cannot be seen in one line. Simplify and rewrite and go into more detail in the description. I depend on skimming PR titles to prepare reports of changes.
Don’t turn a PR into a general discussion of something not included in the PR. Make an issue and link to the PR from there.
Write the word
music21
in lowercase in the middle of a sentence and asMusic21
at the beginning of a sentence. Avoid beginning a sentence with a module name, but if it has to be done, write it in lowercase, obviously. In contexts where possible,music21
should be stylized in monospaced (with slab serifs, like old typewriters).
Testing¶
We write doctests and unit tests, and we strive for the total test coverage of the project to increase with every pull request. See the developer docs to dig in to specific topics like adjusting doctests to prevent actions we don’t want executed when running the general test suite (such as opening browser windows or playing music).
Pull requests that increase or improve coverage of existing features are very welcome. Coverage reports can be found at Coveralls. Pull requests that lower overall coverage are likely to be rejected (exception: replace 30 covered lines with 5 covered lines that do the same job more efficiently, and you’ve lowered the overall coverage, but that’s okay).
For changes to file parsing, please test both import and export (when
supported for that format), and please increment the most minor version
number in music21.__version__
so that cached files will be
invalidated. When writing a PR that changes imports, feel free to use
converter.parse(fp, forceSource=True)
so that tests have a chance to
fail locally, but in most cases we will ask you to remove this keyword
when polishing the patch.
Arguments and Keywords in classes, methods, and functions¶
These guidelines come from GitHub issue 1389; any further discussion should take place there.
These guidelines have been in place since music21 v8 (Fall 2022). All older functions can continue as is, but should be updated when possible. The existence of older functions that violates these rules cannot be cited as precedent.
Functions can have no more than 3 positional arguments, and should only include ones used most often.
Methods may have “self” + 3 positional arguments
Any remaining arguments should be keyword only
When adding new functionality to existing functions, nearly always, a keyword-only argument is the right choice.
The order of arguments should make sense: numerator -> denominator, from -> to. If it’s likely to be confused (especially if two variables are the same type), better to use keyword only.
For arbitrary positional and keyword arguments that are not parsed, the names are
*arguments, **keywords
. #1377 has made this rename for**keywords
– this change was easy since**kwargs
is daunting to new users (I remember not knowing what it meant). The choice of*args
vs*arguments
was tough, since*args
is more obvious what it means than**kwargs
, and*arguments
is longer; they are used about equally in existing code. The decision was based on*arguments
being more explicit, AND being longer to type is a slight ADVANTAGE since this Issue discourages using it. And, this should be a moot issue in any case, because of rules below.Functions should NOT look at
**keywords
. See GitHub issue #839 – any members that will be used in the function must be explicitly mentioned in the function signature.So instead of
if 'myOption' in keywords...
putmyOption: t.Optional[Something] = None
in the signature of the function.An exception is granted for multiple inheritance to examine the
**keywords
dict to split it for two different constructors which use the same key to mean something different.Keyword arguments should be keyword-only by using
*
to consume any other positional arguments:def makeNoise(self, volume, *, color=noise.PINK):
Methods can have a generic
**keywords
at the end of the constructor signature which is assumed to be passed up the inheritance chain to the superclass for its own keywords (or its superclass’s own keywords, etc.). This is required for Music21Object subclasses. This way other Music21Objects don’t have to deal withduration
,groups
,style
, etc. and can pass it up the chain. It is especially important forid
since this requires pylint exemptions, etc.The only use of
(*arguments, **keywords)
is for a quick subclass that needs to keep track of something else along the way and we want to avoid the maintenance burden of, e.g., updating Marcato whenever the signature of Music21Object, Articulation, etc. changes. Core and often used subclasses should know what the signatures of their superclasses are and write their constructors accordingly. The use of common.types shortcuts, such as OffsetQL (for types that are allowed as offset or quarterLength values) should be used to avoid writing long and variable types over and over. Even here, don’t use*arguments
if the superclass does not have arguments currently.Aside from the case above
*arguments
should only be used in cases where the number of arguments is actually unlimited, all have the same type as each other, and all have the same meaning. E.g., Chord, has an arbitrary number of Note, Pitch, or string arguments can be passed in separated by commas. Code should not have things like what Tuplet currently has, where*arguments
can only have 2 or 3 entries and the first meansnumNotesActual: int
, the secondnumNotesNormal: int
, and the thirddurationActual: str|DurationTuple
. These can be normal arguments which can be specified by position or keyword.When
*arguments
are used properly (like in Chord) the variable name should reflect the type of thing expected, e.g.,*notes
. (Or in the case of Chord which can also take a list of notes,(self, noteListOrFirstNote, *remainingNotes)
)Use positional-only arguments only when there is a variable type argument like “noteOrStringOrListOfNotes” which you’d rather that users not specify by keyword, AND there are keyword alternates like
n=..., s=..., nList=...
so that people can specify what they are putting in. Interval() has been refactored to use positional-only arguments. In general, do not use positional-only arguments.Document all arguments in the docstring. Arguments that become stored in attributes (not properties) should be documented and tested in
_DOC_ATTR = {}
. Those that are manipulated and not stored directly should be tested in the docstring or unittests.
Finally¶
If you’re looking for ways to get started, browse the issues board, the
Coveralls module coverage, or the TODO stubs in an area of the code that
interests you. Thanks for your interest in contributing to music21
.
We look forward to seeing your work!
(Note that Cuthbert, the principal maintainer of music21
is on
sabbatical from the project until at least January 2024 (but not longer
than July 2024, and for the moment, new requests are not being actively
reviewed).