Skip to content

app_main

Application entry-point infrastructure.

This module provides the main() entry point wiring command-line argument parsing to a main function, the configuration of the library modules requiring command line setup - like alog - and the Main decorator which auto-generates the command line arguments from the signature of the decorated main function.

Note that main() always adds the logging options to the given parser - besides the ones of a Main-decorated function.

Example
import argparse
import py_misc_utils.app_main as am

@am.Main
def run_it(count: int = 5):
  return count * 2

parser = argparse.ArgumentParser()
run_it.add_arguments(parser)
args = parser.parse_args(['--count', '21'])

assert run_it(args) == 42

Main

A decorator auto-generating command line arguments.

Decorating a function with Main makes its parameters become command line arguments: parameters with a default value generate --name options - with type and default derived from the default value - while the ones without it generate positional arguments.

The decorated function keeps its original signature for direct calls, but when used as a main function - via main() - it is called with the parsed arguments.

Parameters annotated with a typing.Literal get the literal values as their choices, bool parameters get a BooleanOptionalAction action, and the parameters without type information get YAML-parsed values.

Use as:

@app_main.Main def my_main(arg, ..., kwarg=17, ...): ...

if name == 'main': parser = argparse.ArgumentParser(...) ... app_main.main(parser, my_main, ...)

Source code in py_misc_utils/app_main.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
class Main:
  """A decorator auto-generating command line arguments.

  Decorating a function with Main makes its parameters become command
  line arguments: parameters with a default value generate --name
  options - with type and default derived from the default value -
  while the ones without it generate positional arguments.

  The decorated function keeps its original signature for direct calls,
  but when used as a main function - via main() - it is called with the
  parsed arguments.

  Parameters annotated with a typing.Literal get the literal values as
  their choices, bool parameters get a BooleanOptionalAction action, and
  the parameters without type information get YAML-parsed values.

  Use as:

    @app_main.Main
    def my_main(arg, ..., kwarg=17, ...):
      ...

    if __name__ == '__main__':
      parser = argparse.ArgumentParser(...)
      ...
      app_main.main(parser, my_main, ...)
  """

  def __init__(self, func):
    """Decorates a main function."""
    self._func = func
    self._sig = inspect.signature(func)
    functools.update_wrapper(self, func)

  def __call__(self, parsed_args):
    """Invokes the decorated function with the parsed arguments.

    Args:
      parsed_args: The parsed command line arguments - whose attributes
        are matched - by name - to the decorated function parameters.
    """
    args, kwargs = [], {}
    for n, p in self._sig.parameters.items():
      pv = getattr(parsed_args, n, None)
      if p.kind == p.POSITIONAL_ONLY:
        args.append(pv)
      else:
        kwargs[n] = pv

    return self._func(*args, **kwargs)

  def add_arguments(self, parser):
    """Adds the command line arguments of the decorated function.

    Args:
      parser: The command line parser to add the arguments to.
    """
    fname = self._func.__name__

    for n, p in self._sig.parameters.items():
      choices = None
      defval = p.default if p.default is not p.empty else None
      if p.annotation is not p.empty:
        ptype = p.annotation
        if typing.get_origin(ptype) == typing.Literal:
          choices = typing.get_args(ptype)
          ptype = type(choices[0])

        type_cast = functools.partial(cu.to_type, vtype=ptype)
      elif defval is not None:
        ptype = type(defval)
        type_cast = functools.partial(cu.to_type, vtype=ptype)
      else:
        ptype, type_cast = str, yaml.safe_load

      action = argparse.BooleanOptionalAction if ptype is bool else None

      help_str = f'Argument "{n}" (type={ptype.__name__}) of function {fname}(...)'
      if p.default is p.empty or p.kind == p.POSITIONAL_ONLY:
        parser.add_argument(n,
                            metavar=n.upper(),
                            action=action,
                            type=type_cast,
                            default=defval,
                            choices=choices,
                            help=help_str)
      else:
        parser.add_argument(f'--{n}',
                            action=action,
                            type=type_cast,
                            default=defval,
                            choices=choices,
                            help=help_str)

add_arguments(parser)

Adds the command line arguments of the decorated function.

Parameters:

Name Type Description Default
parser

The command line parser to add the arguments to.

required
Source code in py_misc_utils/app_main.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def add_arguments(self, parser):
  """Adds the command line arguments of the decorated function.

  Args:
    parser: The command line parser to add the arguments to.
  """
  fname = self._func.__name__

  for n, p in self._sig.parameters.items():
    choices = None
    defval = p.default if p.default is not p.empty else None
    if p.annotation is not p.empty:
      ptype = p.annotation
      if typing.get_origin(ptype) == typing.Literal:
        choices = typing.get_args(ptype)
        ptype = type(choices[0])

      type_cast = functools.partial(cu.to_type, vtype=ptype)
    elif defval is not None:
      ptype = type(defval)
      type_cast = functools.partial(cu.to_type, vtype=ptype)
    else:
      ptype, type_cast = str, yaml.safe_load

    action = argparse.BooleanOptionalAction if ptype is bool else None

    help_str = f'Argument "{n}" (type={ptype.__name__}) of function {fname}(...)'
    if p.default is p.empty or p.kind == p.POSITIONAL_ONLY:
      parser.add_argument(n,
                          metavar=n.upper(),
                          action=action,
                          type=type_cast,
                          default=defval,
                          choices=choices,
                          help=help_str)
    else:
      parser.add_argument(f'--{n}',
                          action=action,
                          type=type_cast,
                          default=defval,
                          choices=choices,
                          help=help_str)

main(parser, mainfn, args=None, rem_args=None)

Runs a main function with a command line parser.

The init modules are configured with the parsed arguments - and the Main-decorated main functions add their own arguments to the parser - before the main function is invoked.

The parsed arguments are stored in the process global namespace, so that they are available to forked child processes as well.

Parameters:

Name Type Description Default
parser

The command line parser to use.

required
mainfn

The main function to run: either a plain callable taking the parsed arguments, or a Main-decorated function.

required
args

An optional list of command line arguments to parse - the process arguments by default.

None
rem_args

An optional attribute name the arguments following a '--' separator are stored into - as a tuple.

None
Source code in py_misc_utils/app_main.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def main(parser, mainfn, args=None, rem_args=None):
  """Runs a main function with a command line parser.

  The init modules are configured with the parsed arguments - and the
  Main-decorated main functions add their own arguments to the parser -
  before the main function is invoked.

  The parsed arguments are stored in the process global namespace, so
  that they are available to forked child processes as well.

  Args:
    parser: The command line parser to use.
    mainfn: The main function to run: either a plain callable taking the
      parsed arguments, or a Main-decorated function.
    args: An optional list of command line arguments to parse - the
      process arguments by default.
    rem_args: An optional attribute name the arguments following a '--'
      separator are stored into - as a tuple.
  """
  mp.procfn_wrap(_main, parser, mainfn, args, rem_args)

basic_main(mainfn, description='Basic Main')

Runs a main function with a basic command line parser.

Parameters:

Name Type Description Default
mainfn

The main function to run.

required
description

The description of the command line parser.

'Basic Main'
Source code in py_misc_utils/app_main.py
148
149
150
151
152
153
154
155
156
157
158
159
def basic_main(mainfn, description='Basic Main'):
  """Runs a main function with a basic command line parser.

  Args:
    mainfn: The main function to run.
    description: The description of the command line parser.
  """
  parser = argparse.ArgumentParser(
      description=description,
      formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  )
  main(parser, mainfn)

add_setupfn(setupfn, run=True)

Registers a setup function run by forked child processes.

Parameters:

Name Type Description Default
setupfn

The setup function to register.

required
run

Whether the setup function is run also in the registering process - it is always run in the forked children.

True
Source code in py_misc_utils/app_main.py
182
183
184
185
186
187
188
189
190
191
192
193
194
def add_setupfn(setupfn, run=True):
  """Registers a setup function run by forked child processes.

  Args:
    setupfn: The setup function to register.
    run: Whether the setup function is run also in the registering
      process - it is always run in the forked children.
  """
  if run:
    setupfn()

  setup_functions = gns.get(_SETUP_FUNCTIONS)
  setup_functions.append(setupfn)