0

Is there a conventional manner for referencing argument identifiers in assertion messages? For example:

def func(x):
  assert x > 0, "x must be positive"

or is it

def func(x):
  assert x > 0, "'x' must be positive"

or possibly

def func(x):
  assert x > 0, "`x` must be positive"

Calling func(-1) on each of these returns the following, respectively:

>>> AssertionError: x must be positive
>>> AssertionError: 'x' must be positive
>>> AssertionError: `x` must be positive

Are there any conventions to this in Python software, or is it mostly irrelevant?

Ryan Rudes
  • 508
  • 4
  • 11
  • If I had to choose between your three I would say the third, in this case, for an undescriptive variable name `x`. However, the ideal scenario would be to put _what the variable is meant to represent_ in the error as well (e.g. if `func(x)` calculated the `x`th fibonacci number, then say `'Desired fibonacci number \`x\` must be positive'`) – Green Cloak Guy Feb 17 '21 at 16:07
  • I don't think there's any conventions about the wordings of exception messages. However, I would not use `assert` for this purpose. Typically you would raise the builtin ValueError or a custom exception. Read the answers to this question for further explanation of when to use `assert`. https://stackoverflow.com/questions/5142418/what-is-the-use-of-assert – Håken Lid Feb 17 '21 at 16:12

0 Answers0