if statement - Python - Parameter checking with Exception Raising -


i attempting write exception raising code blocks python code in order ensure parameters passed function meet appropriate conditions (i.e. making parameters mandatory, type-checking parameters, establishing boundary values parameters, etc...). understand satisfactorily how manually raise exceptions handling them.

from numbers import number  def foo(self, param1 = none, param2 = 0.0, param3 = 1.0):    if (param1 == none):       raise valueerror('this parameter mandatory')    elif (not isinstance(param2, number)):       raise valueerror('this parameter must valid numerical value')    elif (param3 <= 0.0):       raise valueerror('this parameter must positive number')    ... 

this acceptable (tried , true) way of parameter checking in python, have wonder: since python not have way of writing switch-cases besides if-then-else statements, there more efficient or proper way perform task? or implementing long stretches of if-then-else statements option?

you create decorator function , pass expected types , (optional) ranges parameters. this:

def typecheck(types, ranges=none):     def __f(f):         def _f(*args, **kwargs):             a, t in zip(args, types):                 if not isinstance(a, t):                     raise valueerror("expected %s got %r" % (t, a))             a, r in zip(args, ranges or []):                 if r , not r[0] <= <= r[1]:                     raise valueerror("should in range %r: %r" % (r, a))             return f(*args, **kwargs)         return _f     return __f 

instead of if ...: raise invert conditions , use assert, noted in comments might not executed. extend allow e.g. open ranges (like (0., none)) or accept arbitrary (lambda) functions more specific checks.

example:

@typecheck(types=[int, float, str], ranges=[none, (0.0, 1.0), ("a", "f")]) def foo(x, y, z):     print("called foo ", x, y, z)  foo(10, .5, "b")  # called foo  10 0.5 b foo([1,2,3], .5, "b")  # valueerror: expected <class 'int'>, got [1, 2, 3] foo(1, 2.,"e")  # valueerror: should in range (0.0, 1.0): 2.0 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -