Parser Base Implementation¶
Implementation of parser base classes upon which actual parsers are built.
Functions¶
- disnake_compass.impl.parser.base.get_parser(type_)[source]¶
Get the default parser for the provided type.
Note that type annotations such as
Union[int, str]are also valid.
- disnake_compass.impl.parser.base.register_parser(parser, *types, priority=0, force=True)[source]¶
Register a parser class as the default parser for the provided type.
The default parser will automatically be used for any field annotated with that type. For example, the default parser for integers is
disnake_compass.IntParser, an instance of which will automatically be assigned to any custom id fields annotated with int.- Parameters:
Classes¶
- clsdefault
- clsdefault_types
- asyncdumps
- asyncloads
- class disnake_compass.impl.parser.base.Parser(*args, **kwargs)[source]¶
Bases:
Parser[ParserType],Protocol[ParserType]Class that handles parsing of one custom id field to and from a desired type.
A parser contains two main methods,
loads()anddumps().loads, likejson.loads()serves to turn a string value into a different type. Similarly,dumpsserves to convert that type back into a string.Methods¶
- classmethod default(target_type, /)[source]¶
Return the default implementation of this parser type.
By default, this will just create the parser class with no arguments, but this can be overwritten on child classes for customised behaviour.
- classmethod default_types()[source]¶
Return the types for which this parser type is the default implementation.
- Returns:
The types for which this parser type is the default implementation.
- Return type:
Sequence[type]
- await dumps(argument, /)[source]¶
Dump a value from a given type and convert it to a string.
In most cases it is imperative to ensure that this is done in a reversible way, such that calling
loads()on the result of this function returns the original input. For example:>>> parser = IntParser() >>> input_str = "1" >>> parsed_int = parser.loads(input_str) >>> dumped_int = parser.dumps(parsed_int) >>> input_str == dumped_int True
Any errors raised inside this method remain unmodified, and should be handled externally.
- Parameters:
argument (
ParserType) – The argument to parse into the desired type.- Returns:
- await loads(argument, /)[source]¶
Load a value from a string and apply the necessary conversion logic.
Any errors raised inside this method remain unmodified, and should be handled externally.
- Parameters:
argument (
Any) – The argument to parse into the desired type.- Returns:
ParserType– In case the parser method was sync, the parsed result is returned as-is.Coroutine[ParserType] – In case the parser method was async, the parser naturally returns a coroutine. Awaiting this coroutine returns the parser result.