A group of options shown in its own section.
| 320 | |
| 321 | |
| 322 | class OptionGroup: |
| 323 | """A group of options shown in its own section.""" |
| 324 | |
| 325 | def __init__( |
| 326 | self, |
| 327 | arggroup: argparse._ArgumentGroup, |
| 328 | name: str, |
| 329 | parser: Parser | None, |
| 330 | _ispytest: bool = False, |
| 331 | ) -> None: |
| 332 | check_ispytest(_ispytest) |
| 333 | self._arggroup = arggroup |
| 334 | self.name = name |
| 335 | self.options: list[Argument] = [] |
| 336 | self.parser = parser |
| 337 | |
| 338 | def addoption(self, *opts: str, **attrs: Any) -> None: |
| 339 | """Add an option to this group. |
| 340 | |
| 341 | If a shortened version of a long option is specified, it will |
| 342 | be suppressed in the help. ``addoption('--twowords', '--two-words')`` |
| 343 | results in help showing ``--two-words`` only, but ``--twowords`` gets |
| 344 | accepted **and** the automatic destination is in ``args.twowords``. |
| 345 | |
| 346 | :param opts: |
| 347 | Option names, can be short or long options. |
| 348 | Note that lower-case short options (e.g. `-x`) are reserved. |
| 349 | :param attrs: |
| 350 | Same attributes as the argparse library's :meth:`add_argument() |
| 351 | <argparse.ArgumentParser.add_argument>` function accepts. |
| 352 | """ |
| 353 | conflict = set(opts).intersection( |
| 354 | name for opt in self.options for name in opt.names() |
| 355 | ) |
| 356 | if conflict: |
| 357 | raise ValueError(f"option names {conflict} already added") |
| 358 | self._addoption_inner(opts, attrs, allow_reserved=False) |
| 359 | |
| 360 | def _addoption(self, *opts: str, **attrs: Any) -> None: |
| 361 | """Like addoption(), but also allows registering short lower case options (e.g. -x), |
| 362 | which are reserved for pytest core.""" |
| 363 | self._addoption_inner(opts, attrs, allow_reserved=True) |
| 364 | |
| 365 | def _addoption_inner( |
| 366 | self, opts: tuple[str, ...], attrs: dict[str, Any], allow_reserved: bool |
| 367 | ) -> None: |
| 368 | if not allow_reserved: |
| 369 | for opt in opts: |
| 370 | if len(opt) >= 2 and opt[0] == "-" and opt[1].islower(): |
| 371 | raise ValueError("lowercase short options are reserved") |
| 372 | |
| 373 | action = self._arggroup.add_argument(*opts, **attrs) |
| 374 | option = Argument(action) |
| 375 | self.options.append(option) |
| 376 | if self.parser: |
| 377 | for name in option.names(): |
| 378 | self.parser._opt2dest[name] = option.dest |
| 379 | self.parser.processoption(option) |