how to implicitly check method arguments in python -
i have written library uses user defined class calculates defined properties in custom formula way. later user defined formulas used in library functions. formulas have permitted range common argument. user therefore has define minimal , maximal permitted argument values. before usage important check permitted argument range.
the code below shows how done. user has write subclass class arguments min
, max
set_all_attributes()
method. in method can implement custom code , has explicitly call check_value_range()
method. subclassing needs boilerplate code, user has write each of many custom subclasses. call of check_value_range()
method.
now question: there better way implement boundary checking? may possible call check implicitly of metaclass? performance reasons, check should done once class attributes.
from abc import abcmeta, abstractmethod class base: __metaclass__ = abcmeta def __init__(self, init_value=0): self.a = init_value self.b = init_value self.c = init_value def check_value_range(self, value): """make sure value in permitted range""" if value < self.min or value > self.max: raise valueerror('value not in permitted range!') @abstractmethod def set_all_attributes(self, value): """force subclasses override method""" pass class userdefinedsubclass(base): """user has define min , max class arguments set_all_attributes() method""" min = 0 max = 10 def set_all_attributes(self, value): """the user has explicitly call check_value_range() method""" self.check_value_range(value) self.a = 1+2*value self.b = 2+5*value self.c = 3+4*value def some_library_function(user_class): u = user_class() u.set_all_attributes(2) return u.a + u.b + u.c # usage print some_library_function(userdefinedsubclass)
Comments
Post a Comment