Skip to content

Commit

Permalink
events/configurations/? => Duration: Allow strings
Browse files Browse the repository at this point in the history
This patch allows the usage of strings in the default duration parser.
With this patch the following syntax is allowed:

>>> from mutwo import core_events
>>> core_events.SimpleEvent('3/2')    # fractions
>>> core_events.SimpleEvent('4.213')  # floats

Particularly fractions can be useful for precisely writing beats
without using the long-named 'fractions.Fraction' and without the
danger of floating point errors.
  • Loading branch information
levinericzimmermann committed Sep 3, 2023
1 parent 40e4433 commit ff3c0d5
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions mutwo/core_events/configurations.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,34 @@
# directly because it would raise a circular import error.
@functools.cache
def __unknown_object_to_duration():
import typing

from mutwo import core_converters
from mutwo import core_parameters

def raise_parse_error(value: typing.Any):
raise NotImplementedError(f"Can't parse '{value}' to a duration object!")

def string_to_duration(string: str):
if "." in string:
f = float
elif "/" in string:
f = quicktions.Fraction
else:
f = int
try:
v = f(string)
except ValueError:
raise_parse_error(string)
return UNKNOWN_OBJECT_TO_DURATION(v)

return core_converters.UnknownObjectToObject[core_parameters.abc.Duration](
(
(
(float, int, fractions.Fraction, quicktions.Fraction),
core_parameters.DirectDuration,
),
((str,), string_to_duration),
)
)

Expand Down

0 comments on commit ff3c0d5

Please sign in to comment.