Search code examples
pythonmusic21

How to (automatically) difference Opus and Score objects?


I'm working with the 1850 O'Neills Folksong corpus, as it comes on music21 corpus. I need to iterate over all the songs.

I tried using the following code

songs = corpus.getComposer('oneills1850')
for ruta in songs:
    op = converter.parse(ruta)
    numbers = op.getNumbers()

...and then iterate on numbers. In most cases, each op variable is a Opus object, and each of its numbers is associated to a Score.

The problem is that this is not always true. For example, the 15th element of songs (i.e. index 14) is a Score object itself, not Opus. So my code crashes when attemping to use getNumbers.

The solucion, I guess, should be checking beforehand if op is an Opus (and in that case use getNumbers as I done before) or a Score (and in that case skipping that second iteration part). But I can't find how to do that, or any other thing that solves my problem.


Solution

  • If you have to be sure of the type of an object before calling methods on it, use isinstance:

    if isinstance(op,Opus):