On 06/06/2024 19:52, Jeremy Spewock wrote:
+ @classmethod
+ def from_str(cls, text: str):
+ match text:
+ case "black":
+ return cls.BLACK
+ case "white":
+ return cls.WHITE
+ case _:
+ return None # unsupported colour
+
+ @classmethod
+ def make_parser(cls):
+ # make a parser function that finds a match and
+ # then makes it a Colour object through Colour.from_str
+ return TextParser.wrap(cls.from_str, TextParser.find(r"is a
(\w+)"))
I think this example is backwards now that you changed the parameters
to calling order isn't it? We need to call find first and then pass
that into from_str.
aargh! yes, you are right. thank you! and well spotted!
+
+ @dataclass
+ class Animal(TextParser):
+ kind: str = field(metadata=TextParser.find(r"is a \w+ (\w+)"))
+ name: str = field(metadata=TextParser.find(r"^(\w+)"))
+ colour: Colour = field(metadata=Colour.make_parser())
+ age: int = field(metadata=TextParser.find_int(r"aged (\d+)"))
+
+ steph = Animal.parse("Stephanie is a white cat aged 10")
+ print(steph) # Animal(kind='cat', name='Stephanie',
colour=<Colour.WHITE: 2>, age=10)
+ """
+
<snip>
+ @staticmethod
+ def find(
+ pattern: str | re.Pattern[str],
+ flags: re.RegexFlag = re.RegexFlag(0),
+ named: bool = False,
+ ) -> ParserFn:
+ """Makes a parser function that finds a regular expression match in
the text.
+
+ If the pattern has any capturing groups, it returns None if no match
was found, otherwise a
+ tuple containing the values per each group is returned.. If the
pattern has only one
It looks like there are two periods here by mistake.
well spotted again!