Skip to content

Commit

Permalink
Handle options with no default value in get_help_table()
Browse files Browse the repository at this point in the history
Some options may have a default that cannot be evaluated. This means
that the option has to be set explicity when the Options object is
created. Handle this in get_help_table() by printing '*Required*' in
place of these default values.
  • Loading branch information
johnomotani committed Jan 1, 2023
1 parent 04e399a commit 548ff3b
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions optionsfactory/optionsfactory.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,14 +208,31 @@ def get_help_table(self, prefix=None):
if prefix is None:
prefix = ""
defaults = self.defaults
evaluated_defaults = {}

# Need to use self.__create_mutable() here as if any option is required to be
# set then calling self.create() would cause an error (actually the error we
# want to catch and handle case-by-case in the try-except below).
mutable_options = self.__create_mutable()
for k, v in defaults.items():
try:
evaluated = v.evaluate_expression(mutable_options)
except (ValueError, TypeError):
# If the default value cannot be evaluated, it is required to be set in
# `values` when the Options or MutableOptions are created
evaluated = "*Required*"
evaluated_defaults[k] = evaluated

keys = sorted(defaults.keys())
docs = self.doc
heading1 = "Option"
heading2 = "Description"
heading3 = "Default"
column1_width = max(max(len(k) for k in keys), len(heading1))
column2_width = max(max(len(str(d)) for d in docs.values()), len(heading2))
column3_width = max(max(len(str(d)) for d in defaults.values()), len(heading3))
column3_width = max(
max(len(str(d)) for d in evaluated_defaults.values()), len(heading3)
)
separator = (
prefix
+ "+"
Expand Down Expand Up @@ -257,9 +274,7 @@ def get_help_table(self, prefix=None):
+ "|"
+ str(docs[k]).ljust(column2_width)
+ "|"
+ str(defaults[k].evaluate_expression(self.create())).ljust(
column3_width
)
+ str(evaluated_defaults[k]).ljust(column3_width)
+ "|\n"
)
table = table + separator
Expand Down

0 comments on commit 548ff3b

Please sign in to comment.