memo: Python | Parse Input Args

vars()

  1. Create a class ParamGroup to store args into instance variables, then use vars(self) to read memebers from self.__dict__.

  2. Add each argument into parser through parser.add_argument().

  3. Set shorthand to the initial character, e.g., --source_path use -s

Example from gaussian-splatting:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class ParamGroup:
  def __init__(self, parser: ArgumentParser, name : str, fill_none = False):
    group = parser.add_argument_group(name)
    for key, value in vars(self).items():
      shorthand = False
      if key.startswith("_"):
          shorthand = True
          key = key[1:]
      t = type(value)
      value = value if not fill_none else None 

      if shorthand:
          if t == bool:
              group.add_argument("--" + key, ("-" + key[0:1]), default=value, action="store_true")
          else:
              group.add_argument("--" + key, ("-" + key[0:1]), default=value, type=t)
      else:
          if t == bool:
              group.add_argument("--" + key, default=value, action="store_true")
          else:
              group.add_argument("--" + key, default=value, type=t)

class ModelParams(ParamGroup): 
  def __init__(self, parser, sentinel=False):
    self.sh_degree = 3
    self._source_path = ""
    self._model_path = ""
    self._images = "images"
    self._resolution = -1
    self._white_background = False
    self.data_device = "cuda"
    self.eval = False
    super().__init__(parser, "Loading Parameters", sentinel)

(2024-04-03)

  • In this way, there won’t be a long list of parser.add_argument() declaiming all arguments.

    Instead, related arguments are arranged into a group.


Customize Parsing

(2023-09-27)

  1. Analyse string manually

    Refer to Match-NeRF for an example.