argutils.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from pathlib import Path
  2. import numpy as np
  3. import argparse
  4. _type_priorities = [ # In decreasing order
  5. Path,
  6. str,
  7. int,
  8. float,
  9. bool,
  10. ]
  11. def _priority(o):
  12. p = next((i for i, t in enumerate(_type_priorities) if type(o) is t), None)
  13. if p is not None:
  14. return p
  15. p = next((i for i, t in enumerate(_type_priorities) if isinstance(o, t)), None)
  16. if p is not None:
  17. return p
  18. return len(_type_priorities)
  19. def print_args(args: argparse.Namespace, parser=None):
  20. args = vars(args)
  21. if parser is None:
  22. priorities = list(map(_priority, args.values()))
  23. else:
  24. all_params = [a.dest for g in parser._action_groups for a in g._group_actions ]
  25. priority = lambda p: all_params.index(p) if p in all_params else len(all_params)
  26. priorities = list(map(priority, args.keys()))
  27. pad = max(map(len, args.keys())) + 3
  28. indices = np.lexsort((list(args.keys()), priorities))
  29. items = list(args.items())
  30. print("Arguments:")
  31. for i in indices:
  32. param, value = items[i]
  33. print(" {0}:{1}{2}".format(param, ' ' * (pad - len(param)), value))
  34. print("")