Defines a new command line option. ``type`` can be any of `str`, `int`, `float`, `bool`, `~datetime.datetime`, or `~datetime.timedelta`. If no ``type`` is given but a ``default`` is, ``type`` is the type of ``default``. Otherwise, ``type`` defaults to `str`.
(
self,
name: str,
default: Any = None,
type: Optional[type] = None,
help: Optional[str] = None,
metavar: Optional[str] = None,
multiple: bool = False,
group: Optional[str] = None,
callback: Optional[Callable[[Any], None]] = None,
)
| 221 | return dict((opt.name, opt.value()) for name, opt in self._options.items()) |
| 222 | |
| 223 | def define( |
| 224 | self, |
| 225 | name: str, |
| 226 | default: Any = None, |
| 227 | type: Optional[type] = None, |
| 228 | help: Optional[str] = None, |
| 229 | metavar: Optional[str] = None, |
| 230 | multiple: bool = False, |
| 231 | group: Optional[str] = None, |
| 232 | callback: Optional[Callable[[Any], None]] = None, |
| 233 | ) -> None: |
| 234 | """Defines a new command line option. |
| 235 | |
| 236 | ``type`` can be any of `str`, `int`, `float`, `bool`, |
| 237 | `~datetime.datetime`, or `~datetime.timedelta`. If no ``type`` |
| 238 | is given but a ``default`` is, ``type`` is the type of |
| 239 | ``default``. Otherwise, ``type`` defaults to `str`. |
| 240 | |
| 241 | If ``multiple`` is True, the option value is a list of ``type`` |
| 242 | instead of an instance of ``type``. |
| 243 | |
| 244 | ``help`` and ``metavar`` are used to construct the |
| 245 | automatically generated command line help string. The help |
| 246 | message is formatted like:: |
| 247 | |
| 248 | --name=METAVAR help string |
| 249 | |
| 250 | ``group`` is used to group the defined options in logical |
| 251 | groups. By default, command line options are grouped by the |
| 252 | file in which they are defined. |
| 253 | |
| 254 | Command line option names must be unique globally. |
| 255 | |
| 256 | If a ``callback`` is given, it will be run with the new value whenever |
| 257 | the option is changed. This can be used to combine command-line |
| 258 | and file-based options:: |
| 259 | |
| 260 | define("config", type=str, help="path to config file", |
| 261 | callback=lambda path: parse_config_file(path, final=False)) |
| 262 | |
| 263 | With this definition, options in the file specified by ``--config`` will |
| 264 | override options set earlier on the command line, but can be overridden |
| 265 | by later flags. |
| 266 | |
| 267 | """ |
| 268 | normalized = self._normalize_name(name) |
| 269 | if normalized in self._options: |
| 270 | raise Error( |
| 271 | "Option %r already defined in %s" |
| 272 | % (normalized, self._options[normalized].file_name) |
| 273 | ) |
| 274 | frame = sys._getframe(0) |
| 275 | if frame is not None: |
| 276 | options_file = frame.f_code.co_filename |
| 277 | |
| 278 | # Can be called directly, or through top level define() fn, in which |
| 279 | # case, step up above that frame to look for real caller. |
| 280 | if ( |