2

Wanted to get some argument/input with the script and raise an exception when the value is not expected.

To simplify the scenario:

#!/usr/bin/env python3

foo = None or raise ValueError

But the following error was seen:

  File "./raise_on_assignment.py", line 3
    foo = None or raise ValueError
                      ^
SyntaxError: invalid syntax

I know the error could be eliminated by breaking it into multi-lines, like:

#!/usr/bin/env python3

foo = None
if not foo:
    raise ValueError

But, is there a way to make it with a one-liner?

6
  • 1
    You should be able to put your two line solution on one line. You don't gain anything by having it on one line though. The first way fails because raise ValueError isn't an expression. May 21, 2021 at 18:49
  • @Carcigenicate Could you give me an example on how to merge the multi-liner into a one-liner? All I want is to raise an exception when the variable foo is None (meaning the user didn't supply the value for the argument), within the same line.
    – Qiang Xu
    May 21, 2021 at 18:54
  • 1
    Just take your two line code and remove the newline. Again though, you gain nothing by doing that. Smushed code is not necessarily better code. May 21, 2021 at 18:56
  • @Carcigenicate True. That's why I want to know if there is some nicer way to do it, making it compact and easy to understand. Smushing is not my intent.
    – Qiang Xu
    May 21, 2021 at 18:58
  • 1
    if foo is None:<newline>raise ValueError broken over two lines will be the most readable way. If you don't like how it looks, you could wrap that in a function. Something like def assert_truthy(val):<newline>if val is None:<newline>raise ValueError(f"The value was None!"). Then you'd just do assert_truthy(foo) if you want a one-line solution. (Note that <newline> is just me indicating a newline. That is not valid Python syntax). May 21, 2021 at 19:01

1 Answer 1

1

You could get it in 2 lines, for example like this:

foo = None
if foo != None: raise ValueError

I dont think you can define a new value, check an if condition, and raise a ValueError in one line, i still might be wrong.

You should maybe look for ternary operators in python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.