Parsing
This module provides several parsers that convert (usually user-provided)
strings to python objects, or check user input, and throw
ValueError
in case of any issue.
All parsers are descendants of the Parser
class.
On the surface, they are just callables that take a string and return a python
object. That is, you can use them in any place that expects such callable,
for example in flags in argparse, or in ask()
method
from yuio.io
.
When parsing fails, we raise ParsingError
.
Base parser
- class yuio.parse.Parser[source]
Base class for parsers.
- abstract parse(value: str) T [source]
Parse user input, raise
ParsingError
on failure.Don’t forget to call
Parser.validate()
after parsing a value.
- abstract parse_config(value: Any) T [source]
Parse value from a config, raise
ParsingError
on failure.This method accepts python values, i.e. when parsing a json config.
Don’t forget to call
Parser.validate()
after parsing a value.
- abstract validate(value: T)[source]
Verify parsed value, raise
ParsingError
on failure.
- class yuio.parse.ParsingError[source]
Raised when parsing or validation fails.
This exception is derived from both
ValueError
andargparse.ArgumentTypeError
to ensure that error messages are displayed nicely with argparse, and handled correctly in other places.
Value parsers
File system path parsers
- class yuio.parse.Path(extensions: Optional[Collection[str]] = None)[source]
Parse a file system path, return a
pathlib.Path
.
- class yuio.parse.NonExistentPath(extensions: Optional[Collection[str]] = None)[source]
Parse a file system path and verify that it doesn’t exist.
- class yuio.parse.ExistingPath(extensions: Optional[Collection[str]] = None)[source]
Parse a file system path and verify that it exists.
- class yuio.parse.File(extensions: Optional[Collection[str]] = None)[source]
Parse path to a file.
Validators
- class yuio.parse.Bound(inner: Parser[C], *, lower: Optional[C] = None, lower_inclusive: Optional[C] = None, upper: Optional[C] = None, upper_inclusive: Optional[C] = None)[source]
Check that value is upper- or lower-bound by some constraints.
- Parameters
inner – inner parser that will be used to actually parse a value before checking its bounds.
lower – set lower bound for value, so we require that
value > lower
. Can’t be given if lower_inclusive is also given.lower_inclusive – set lower bound for value, so we require that
value >= lower
. Can’t be given if lower is also given.upper – set upper bound for value, so we require that
value < upper
. Can’t be given if upper_inclusive is also given.upper_inclusive – set upper bound for value, so we require that
value <= upper
. Can’t be given if upper is also given.
- class yuio.parse.OneOf(inner: Parser[T], values: Collection[T])[source]
Check if the parsed value is one of the given set of values.