python control parameter type

Python variables can be assigned to any type, so random

In the third-party module of pyExcelerator, I found the code that uses the decorator to limit the parameter type passed to the function, and record it for future reference:

def accepts(*types):
    #print types
    def check_accepts(f):
        assert len(types) == f.func_code.co_argcount
        def new_f(*args, **kwds):
            for (a, t) in zip(args, types):
                assert isinstance(a, t), \
                       "arg %r does not match %s" % (a,t)
            return f(*args, **kwds)
        new_f.func_name = f.func_name
        return new_f
    return check_accepts

@accepts(object, int)
  def set_width(self, value):
      self.__width_twips = value & 0xFFFF

def get_width(self):
      return self.__width_twips

width = property(get_width, set_width)


Check return parameters
def returns(rtype):
    def check_returns(f):
        def new_f(*args, **kwds):
            result = f(*args, **kwds)
            assert isinstance(result, rtype), \
                   "return value %r does not match %s" % (result,rtype)
            return result
        new_f.func_name = f.func_name
        return new_f
    return check_returns

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327016924&siteId=291194637