Parsing context with knowledge of flags & their format. Generally associated with the core program or a task. When run through a parser, will also hold runtime values filled in by the parser. .. versionadded:: 1.0
| 57 | # Named slightly more verbose so Sphinx references can be unambiguous. |
| 58 | # Got real sick of fully qualified paths. |
| 59 | class ParserContext: |
| 60 | """ |
| 61 | Parsing context with knowledge of flags & their format. |
| 62 | |
| 63 | Generally associated with the core program or a task. |
| 64 | |
| 65 | When run through a parser, will also hold runtime values filled in by the |
| 66 | parser. |
| 67 | |
| 68 | .. versionadded:: 1.0 |
| 69 | """ |
| 70 | |
| 71 | def __init__( |
| 72 | self, |
| 73 | name: Optional[str] = None, |
| 74 | aliases: Iterable[str] = (), |
| 75 | args: Iterable[Argument] = (), |
| 76 | ) -> None: |
| 77 | """ |
| 78 | Create a new ``ParserContext`` named ``name``, with ``aliases``. |
| 79 | |
| 80 | ``name`` is optional, and should be a string if given. It's used to |
| 81 | tell ParserContext objects apart, and for use in a Parser when |
| 82 | determining what chunk of input might belong to a given ParserContext. |
| 83 | |
| 84 | ``aliases`` is also optional and should be an iterable containing |
| 85 | strings. Parsing will honor any aliases when trying to "find" a given |
| 86 | context in its input. |
| 87 | |
| 88 | May give one or more ``args``, which is a quick alternative to calling |
| 89 | ``for arg in args: self.add_arg(arg)`` after initialization. |
| 90 | """ |
| 91 | self.args = Lexicon() |
| 92 | self.positional_args: List[Argument] = [] |
| 93 | self.flags = Lexicon() |
| 94 | self.inverse_flags: Dict[str, str] = {} # No need for Lexicon here |
| 95 | self.name = name |
| 96 | self.aliases = aliases |
| 97 | for arg in args: |
| 98 | self.add_arg(arg) |
| 99 | |
| 100 | def __repr__(self) -> str: |
| 101 | aliases = "" |
| 102 | if self.aliases: |
| 103 | aliases = " ({})".format(", ".join(self.aliases)) |
| 104 | name = (" {!r}{}".format(self.name, aliases)) if self.name else "" |
| 105 | args = (": {!r}".format(self.args)) if self.args else "" |
| 106 | return "<parser/Context{}{}>".format(name, args) |
| 107 | |
| 108 | def add_arg(self, *args: Any, **kwargs: Any) -> None: |
| 109 | """ |
| 110 | Adds given ``Argument`` (or constructor args for one) to this context. |
| 111 | |
| 112 | The Argument in question is added to the following dict attributes: |
| 113 | |
| 114 | * ``args``: "normal" access, i.e. the given names are directly exposed |
| 115 | as keys. |
| 116 | * ``flags``: "flaglike" access, i.e. the given names are translated |
no outgoing calls
no test coverage detected
searching dependent graphs…