0

I have some functions in python that I need to verify if some of the arguments is None and raise an Exception otherwise. Currently my solution is:

def notnone(arg):
  if arg == None:
    raise Exception()
  return arg

def example_function(..., a, ...):
  a = notnone(a)
  ...

In python, is there a more elegant solution? As elegant as the decorators are for functions? I'm imagining something like follows (although I know it won't work):

def example_function(..., @notnone a, ...):
  ...
martineau
  • 119,623
  • 25
  • 170
  • 301
LBald
  • 473
  • 2
  • 11

1 Answers1

0

To make sure something is not none inside the function body, you can use:

assert a is not None, "a can't be None"

To make sure something is none, you can use:

assert a is None, "a must be None"

The code execution will halt if condition mismatch.

Also note that positional arguments will never be None unless you explictly pass in None (ie. cannot be left blank during call).

If you know exactly what type the variable is going to be, your best bet for syntax would be type annotations. I don't think the typing module would work for this, because it doesn't provide is not functionality.

idontknow
  • 438
  • 5
  • 16
  • 2
    Do not use `assert` in production code! `assert` statements will be ignored if Python is run in optimization mode. – Klaus D. Jan 14 '21 at 21:26
  • @KlausD: I disagree, `assert`s are fine in production code. – martineau Feb 09 '21 at 01:57
  • @martineau Why? It's ignored in optimization mode. – idontknow Feb 09 '21 at 16:44
  • dontknow: Because one usually wants debugging code removed when a script is put into "production" (which usually implies that the module the code is in being `import`ed), so using `assert` means you don't need two versions of the code. For permanent non-debug code, you'd want to use something else, similar to what the OP is already doing. The documentation for [`assert`](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement) shows what it's equivalent to, so it would be very easy to write ones own `assert`-like function to that would not be removed. – martineau Feb 09 '21 at 18:28
  • See [this answer](https://stackoverflow.com/a/945135/355230) to the question [Best practice for using assert?](https://stackoverflow.com/questions/944592/best-practice-for-using-assert) for a good description of when to use `assert` and when not to. – martineau Feb 09 '21 at 19:04
  • I think I understand what you mean now. But this concept only applies for variables whose type is not determined at runtime. – idontknow Feb 10 '21 at 00:33