Validating Arguments in Python Numeric Code

I find that every time I check the code to check the number:

def myfun(a, b):
    if a < 0:
        raise ValueError('a cannot be < 0 (was a=%s)' % a)
    # more if.. raise exception stuff here ...
    return a + b

Is there a better way? I was told not to use "assert" for these things (although I do not see a problem, except that I do not know the value of the variable that caused the error).

edit: To clarify, the arguments are usually just numbers, and the error checking conditions can be complex, nontrivial and do not necessarily lead to an exception later, but simply to the wrong result. (unstable algorithms, meaningless solutions, etc.)

+3
source share
3 answers

assert , python -O ( , ). , , , - . , , zillion , - ( - ) ; ...

def firstargpos(f):
  def wrapper(first, *args):
    if first < 0:
      raise ValueError(whateveryouwish)
    return f(first, *args)
  return wrapper

- :

@firstargpos  def myfun (a, b):     ...

(, , , ) . , - , (), ( , , , , ! -). , DRY ( "Do not Repeat Yourself" ) , Python , DRY , ! -)

+4

assert, ( ) , (-O ).

, , , , ? , , , , .

0

, , , .

, , , , - . :

def myfun(a, b):
    '''a cannot be < 0'''
    return a + b

. -, , , -, , . -, , , help(myfun), , . , a ? , - , a (, , ), , , . , a + b , , , - .

-1

Source: https://habr.com/ru/post/1721359/


All Articles