Skip to content

Instantly share code, notes, and snippets.

@vst
Created December 29, 2015 07:45
Show Gist options
  • Save vst/3ba495b2a923f6989f4d to your computer and use it in GitHub Desktop.
Save vst/3ba495b2a923f6989f4d to your computer and use it in GitHub Desktop.
from enum import Enum
from math import inf
class Multiplicity(Enum):
"""
Defines multiplicities.
>>> Multiplicity.OPTIONAL.min
0
>>> Multiplicity.OPTIONAL.max
1
>>> Multiplicity.REQUIRED.min
1
>>> Multiplicity.REQUIRED.max
1
>>> Multiplicity.VARIADIC.min
0
>>> Multiplicity.VARIADIC.max
inf
>>> Multiplicity.POLYADIC.min
1
>>> Multiplicity.POLYADIC.max
inf
>>> Multiplicity.alias("?") == Multiplicity.OPTIONAL
True
>>> Multiplicity.alias("1") == Multiplicity.REQUIRED
True
>>> Multiplicity.alias("*") == Multiplicity.VARIADIC
True
>>> Multiplicity.alias("+") == Multiplicity.POLYADIC
True
>>> Multiplicity.alias("X")
Traceback (most recent call last):
...
AttributeError: No such alias defined for multiplicities: X
"""
#: Indicates `0` or `1` multiplicity (`?`).
OPTIONAL = (0, 1)
#: Indicates `1` multiplicity (`1`).
REQUIRED = (1, 1)
#: Indicates `0 or more` multiplicity (`*`).
VARIADIC = (0, inf)
#: Indicates `1 or more` multiplicity (`+`) (Though the name implies 2 or more in maths literature).
POLYADIC = (1, inf)
#: Defines regular expression like aliases for multiplicities.
__ALIASES__ = {
"?": "OPTIONAL",
"1": "REQUIRED",
"*": "VARIADIC",
"+": "POLYADIC"
}
@property
def min(self):
return self.value[0]
@property
def max(self):
return self.value[1]
@classmethod
def alias(cls, symbol: str) -> "Multiplicity":
"""
Returns the multiplicity for the given regular expression like alias.
:param symbol: The regular expression like alias.
:return: The multiplicity for the given alias.
"""
## If we don't have the symbol in the aliases, raise attribure error.
if symbol not in cls.__ALIASES__:
raise AttributeError("No such alias defined for multiplicities: {}".format(symbol))
## Return the multiplicity for the given symbol.
return cls[cls.__ALIASES__[symbol]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment