You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

_checkparam.py 23 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Check parameters."""
  16. import re
  17. import inspect
  18. import math
  19. from enum import Enum
  20. from functools import reduce, wraps
  21. from itertools import repeat
  22. from collections.abc import Iterable
  23. import numpy as np
  24. from mindspore import log as logger
  25. from .common import dtype as mstype
  26. # Named string regular expression
  27. _name_re = r"^\w+[0-9a-zA-Z\_\.]*$"
  28. class Rel(Enum):
  29. """Numerical relationship between variables, logical relationship enumeration definition of range."""
  30. # scalar compare
  31. EQ = 1 # ==
  32. NE = 2 # !=
  33. LT = 3 # <
  34. LE = 4 # <=
  35. GT = 5 # >
  36. GE = 6 # >=
  37. # scalar range check
  38. INC_NEITHER = 7 # (), include neither
  39. INC_LEFT = 8 # [), include left
  40. INC_RIGHT = 9 # (], include right
  41. INC_BOTH = 10 # [], include both
  42. # collection in, not in
  43. IN = 11
  44. NOT_IN = 12
  45. @staticmethod
  46. def get_strs(rel):
  47. """Get value from rel_strs."""
  48. return rel_strs.get(rel, "")
  49. @staticmethod
  50. def get_fns(rel):
  51. """Get value from rel_fns."""
  52. return rel_fns.get(rel, lambda *args: False)
  53. rel_fns = {
  54. # scalar compare
  55. Rel.EQ: lambda x, y: x == y,
  56. Rel.NE: lambda x, y: x != y,
  57. Rel.LT: lambda x, y: x < y,
  58. Rel.LE: lambda x, y: x <= y,
  59. Rel.GT: lambda x, y: x > y,
  60. Rel.GE: lambda x, y: x >= y,
  61. # scalar range check
  62. Rel.INC_NEITHER: lambda x, lower, upper: (lower < x < upper),
  63. Rel.INC_LEFT: lambda x, lower, upper: (lower <= x < upper),
  64. Rel.INC_RIGHT: lambda x, lower, upper: (lower < x <= upper),
  65. Rel.INC_BOTH: lambda x, lower, upper: (lower <= x <= upper),
  66. # collection in, not in
  67. Rel.IN: lambda x, y: x in y,
  68. Rel.NOT_IN: lambda x, y: x not in y,
  69. }
  70. rel_strs = {
  71. # scalar compare
  72. Rel.EQ: "equal to {}",
  73. Rel.NE: "not equal to {}",
  74. Rel.LT: "less than {}",
  75. Rel.LE: "less or equal to {}",
  76. Rel.GT: "greater than {}",
  77. Rel.GE: "greater or equal to {}",
  78. # scalar range check
  79. Rel.INC_NEITHER: "({}, {})",
  80. Rel.INC_LEFT: "[{}, {})",
  81. Rel.INC_RIGHT: "({}, {}]",
  82. Rel.INC_BOTH: "[{}, {}]",
  83. # collection in, not in
  84. Rel.IN: "in {}",
  85. Rel.NOT_IN: "not in {}",
  86. }
  87. class Validator:
  88. """validator for checking input parameters"""
  89. @staticmethod
  90. def check(arg_name, arg_value, value_name, value, rel=Rel.EQ, prim_name=None, excp_cls=ValueError):
  91. """
  92. Method for judging relation between two int values or list/tuple made up of ints.
  93. This method is not suitable for judging relation between floats, since it does not consider float error.
  94. """
  95. rel_fn = Rel.get_fns(rel)
  96. if not rel_fn(arg_value, value):
  97. rel_str = Rel.get_strs(rel).format(f'{value_name}: {value}')
  98. msg_prefix = f'For \'{prim_name}\' the' if prim_name else "The"
  99. raise excp_cls(f'{msg_prefix} `{arg_name}` should be {rel_str}, but got {arg_value}.')
  100. @staticmethod
  101. def check_integer(arg_name, arg_value, value, rel, prim_name):
  102. """Integer value judgment."""
  103. rel_fn = Rel.get_fns(rel)
  104. type_mismatch = not isinstance(arg_value, int) or isinstance(arg_value, bool)
  105. excp_cls = TypeError if type_mismatch else ValueError
  106. if type_mismatch or not rel_fn(arg_value, value):
  107. rel_str = Rel.get_strs(rel).format(value)
  108. msg_prefix = f'For \'{prim_name}\' the' if prim_name else "The"
  109. raise excp_cls(f'{msg_prefix} `{arg_name}` should be an int and must {rel_str}, but got `{arg_value}`'
  110. f' with type `{type(arg_value).__name__}`.')
  111. return arg_value
  112. @staticmethod
  113. def check_number(arg_name, arg_value, value, rel, prim_name):
  114. """Integer value judgment."""
  115. rel_fn = Rel.get_fns(rel)
  116. if not rel_fn(arg_value, value):
  117. rel_str = Rel.get_strs(rel).format(value)
  118. raise ValueError(f'For \'{prim_name}\' the `{arg_name}` must {rel_str}, but got {arg_value}.')
  119. return arg_value
  120. @staticmethod
  121. def check_int_range(arg_name, arg_value, lower_limit, upper_limit, rel, prim_name):
  122. """Method for checking whether an int value is in some range."""
  123. rel_fn = Rel.get_fns(rel)
  124. type_mismatch = not isinstance(arg_value, int)
  125. excp_cls = TypeError if type_mismatch else ValueError
  126. if type_mismatch or not rel_fn(arg_value, lower_limit, upper_limit):
  127. rel_str = Rel.get_strs(rel).format(lower_limit, upper_limit)
  128. raise excp_cls(f'For \'{prim_name}\' the `{arg_name}` should be an int in range {rel_str},'
  129. f' but got `{arg_value}` with type `{type(arg_value).__name__}`.')
  130. return arg_value
  131. @staticmethod
  132. def check_number_range(arg_name, arg_value, lower_limit, upper_limit, rel, prim_name):
  133. """Method for checking whether a numeric value is in some range."""
  134. rel_fn = Rel.get_fns(rel)
  135. if not rel_fn(arg_value, lower_limit, upper_limit):
  136. rel_str = Rel.get_strs(rel).format(lower_limit, upper_limit)
  137. raise ValueError(f'For \'{prim_name}\' the `{arg_name}` should be in range {rel_str}, but got {arg_value}.')
  138. return arg_value
  139. @staticmethod
  140. def check_string(arg_name, arg_value, valid_values, prim_name):
  141. """Checks whether a string is in some value list"""
  142. if isinstance(arg_value, str) and arg_value in valid_values:
  143. return arg_value
  144. if len(valid_values) == 1:
  145. raise ValueError(f'For \'{prim_name}\' the `{arg_name}` should be str and must be {valid_values[0]},'
  146. f' but got {arg_value}.')
  147. raise ValueError(f'For \'{prim_name}\' the `{arg_name}` should be str and must be one of {valid_values},'
  148. f' but got {arg_value}.')
  149. @staticmethod
  150. def check_pad_value_by_mode(pad_mode, padding, prim_name):
  151. """Validates value of padding according to pad_mode"""
  152. if pad_mode != 'pad' and padding != 0:
  153. raise ValueError(f"For '{prim_name}', padding must be zero when pad_mode is '{pad_mode}'.")
  154. return padding
  155. @staticmethod
  156. def check_float_positive(arg_name, arg_value, prim_name):
  157. """Float type judgment."""
  158. msg_prefix = f'For \'{prim_name}\' the' if prim_name else "The"
  159. if isinstance(arg_value, float):
  160. if arg_value > 0:
  161. return arg_value
  162. raise ValueError(f"{msg_prefix} `{arg_name}` must be positive, but got {arg_value}.")
  163. raise TypeError(f"{msg_prefix} `{arg_name}` must be float.")
  164. @staticmethod
  165. def check_subclass(arg_name, type_, template_type, prim_name):
  166. """Checks whether some type is subclass of another type"""
  167. if not isinstance(template_type, Iterable):
  168. template_type = (template_type,)
  169. if not any([mstype.issubclass_(type_, x) for x in template_type]):
  170. type_str = (type(type_).__name__ if isinstance(type_, (tuple, list)) else "") + str(type_)
  171. raise TypeError(f'For \'{prim_name}\' the type of `{arg_name}` should be subclass'
  172. f' of {",".join((str(x) for x in template_type))}, but got {type_str}.')
  173. @staticmethod
  174. def check_const_input(arg_name, arg_value, prim_name):
  175. """Checks valid value."""
  176. if arg_value is None:
  177. raise ValueError(f'For \'{prim_name}\' the `{arg_name}` must be a const input, but got {arg_value}.')
  178. @staticmethod
  179. def check_type_same(args, valid_values, prim_name):
  180. """Checks whether the types of inputs are the same."""
  181. def _check_tensor_type(arg):
  182. arg_key, arg_val = arg
  183. elem_type = arg_val
  184. if not elem_type in valid_values:
  185. type_names = []
  186. for t in valid_values:
  187. type_names.append(str(t))
  188. types_info = '[' + ', '.join(type_names) + ']'
  189. raise TypeError(f'For \'{prim_name}\' type of `{arg_key}` should be in {types_info},'
  190. f' but got {elem_type}.')
  191. return (arg_key, elem_type)
  192. def _check_types_same(arg1, arg2):
  193. arg1_name, arg1_type = arg1
  194. arg2_name, arg2_type = arg2
  195. if arg1_type != arg2_type:
  196. raise TypeError(f'For \'{prim_name}\' type of `{arg2_name}` should be same as `{arg1_name}`,'
  197. f' but `{arg1_name}` with type {arg1_type} and `{arg2_name}` with type {arg2_type}.')
  198. return arg1
  199. elem_types = map(_check_tensor_type, args.items())
  200. reduce(_check_types_same, elem_types)
  201. @staticmethod
  202. def check_tensor_type_same(args, valid_values, prim_name):
  203. """Checks whether the element types of input tensors are the same."""
  204. tensor_types = [mstype.tensor_type(t) for t in valid_values]
  205. Validator.check_type_same(args, tensor_types, prim_name)
  206. @staticmethod
  207. def check_scalar_or_tensor_type_same(args, valid_values, prim_name, allow_mix=False):
  208. """
  209. Checks whether the types of inputs are the same. If the input args are tensors, checks their element types.
  210. If `allow_mix` is True, Tensor(float32) and float32 are type compatible, otherwise an exception will be raised.
  211. """
  212. def _check_argument_type(arg):
  213. arg_key, arg_val = arg
  214. if isinstance(arg_val, type(mstype.tensor)):
  215. arg_val = arg_val.element_type()
  216. if not arg_val in valid_values:
  217. raise TypeError(f'For \'{prim_name}\' the `{arg_key}` should be in {valid_values},'
  218. f' but `{arg_key}` is {arg_val}.')
  219. return arg
  220. def _check_types_same(arg1, arg2):
  221. arg1_name, arg1_type = arg1
  222. arg2_name, arg2_type = arg2
  223. except_flag = False
  224. if isinstance(arg1_type, type(mstype.tensor)) and isinstance(arg2_type, type(mstype.tensor)):
  225. arg1_type = arg1_type.element_type()
  226. arg2_type = arg2_type.element_type()
  227. elif not (isinstance(arg1_type, type(mstype.tensor)) or isinstance(arg2_type, type(mstype.tensor))):
  228. pass
  229. elif allow_mix:
  230. arg1_type = arg1_type.element_type() if isinstance(arg1_type, type(mstype.tensor)) else arg1_type
  231. arg2_type = arg2_type.element_type() if isinstance(arg2_type, type(mstype.tensor)) else arg2_type
  232. else:
  233. except_flag = True
  234. if except_flag or arg1_type != arg2_type:
  235. raise TypeError(f'For \'{prim_name}\' type of `{arg2_name}` should be same as `{arg1_name}`,'
  236. f' but `{arg1_name}` is {arg1_type} and `{arg2_name}` is {arg2_type}.')
  237. return arg1
  238. reduce(_check_types_same, map(_check_argument_type, args.items()))
  239. @staticmethod
  240. def check_value_type(arg_name, arg_value, valid_types, prim_name):
  241. """Checks whether a value is instance of some types."""
  242. valid_types = valid_types if isinstance(valid_types, Iterable) else (valid_types,)
  243. def raise_error_msg():
  244. """func for raising error message when check failed"""
  245. type_names = [t.__name__ for t in valid_types]
  246. num_types = len(valid_types)
  247. msg_prefix = f'For \'{prim_name}\' the' if prim_name else 'The'
  248. raise TypeError(f'{msg_prefix} type of `{arg_name}` should be {"one of " if num_types > 1 else ""}'
  249. f'{type_names if num_types > 1 else type_names[0]}, but got {type(arg_value).__name__}.')
  250. # Notice: bool is subclass of int, so `check_value_type('x', True, [int])` will check fail, and
  251. # `check_value_type('x', True, [bool, int])` will check pass
  252. if isinstance(arg_value, bool) and bool not in tuple(valid_types):
  253. raise_error_msg()
  254. if isinstance(arg_value, tuple(valid_types)):
  255. return arg_value
  256. raise_error_msg()
  257. @staticmethod
  258. def check_type_name(arg_name, arg_type, valid_types, prim_name):
  259. """Checks whether a type in some specified types"""
  260. valid_types = valid_types if isinstance(valid_types, Iterable) else (valid_types,)
  261. def get_typename(t):
  262. return t.__name__ if hasattr(t, '__name__') else str(t)
  263. if arg_type in valid_types:
  264. return arg_type
  265. type_names = [get_typename(t) for t in valid_types]
  266. msg_prefix = f'For \'{prim_name}\' the' if prim_name else 'The'
  267. if len(valid_types) == 1:
  268. raise TypeError(f'{msg_prefix} type of `{arg_name}` should be {type_names[0]},'
  269. f' but got {get_typename(arg_type)}.')
  270. raise TypeError(f'{msg_prefix} type of `{arg_name}` should be one of {type_names},'
  271. f' but got {get_typename(arg_type)}.')
  272. @staticmethod
  273. def check_float_legal_value(arg_name, arg_value, prim_name):
  274. """Checks whether a legal value of float type"""
  275. msg_prefix = f'For \'{prim_name}\' the' if prim_name else "The"
  276. if isinstance(arg_value, float):
  277. if math.isinf(arg_value) or math.isnan(arg_value):
  278. raise ValueError(f"{msg_prefix} `{arg_name}` must be legal value, but got {arg_value}.")
  279. return arg_value
  280. raise TypeError(f"{msg_prefix} `{arg_name}` must be float.")
  281. def check_int(input_param):
  282. """Int type judgment."""
  283. if isinstance(input_param, int) and not isinstance(input_param, bool):
  284. return input_param
  285. raise TypeError("Input type must be int!")
  286. def check_int_positive(input_param):
  287. """Int type judgment."""
  288. if isinstance(input_param, bool):
  289. raise TypeError("Input type must be int cannot be bool!")
  290. if isinstance(input_param, int):
  291. if input_param > 0:
  292. return input_param
  293. raise ValueError("The input_param must be positive, but got input_param {}.".format(input_param))
  294. raise TypeError("Input type must be int cannot be {}!".format(type(input_param)))
  295. def check_int_non_negative(input_param):
  296. """Non_negative type judgment."""
  297. if isinstance(input_param, bool):
  298. raise TypeError("Input type must be int cannot be bool!")
  299. if isinstance(input_param, int):
  300. if input_param >= 0:
  301. return input_param
  302. raise ValueError("The input_param must be non_negative, but got input_param {}.".format(input_param))
  303. raise TypeError("Input type must be int cannot be {}!".format(type(input_param)))
  304. def check_int_zero_one(input_param):
  305. """Judge whether it is 0 or 1."""
  306. if input_param in (0, 1):
  307. return input_param
  308. raise ValueError("The data must be 0 or 1.")
  309. def check_bool(input_param):
  310. """Bool type judgment."""
  311. if isinstance(input_param, bool):
  312. return input_param
  313. raise TypeError("Input type must be bool!")
  314. def check_input_format(input_param):
  315. """Judge input format."""
  316. if input_param == "NCHW":
  317. return input_param
  318. raise ValueError("The data format must be NCHW.")
  319. def check_padding(padding):
  320. """Check padding."""
  321. if padding >= 0:
  322. return padding
  323. raise ValueError("The padding must be at least 0,"" but got padding {}.".format(padding))
  324. def check_padmode(mode):
  325. """Check padmode."""
  326. if mode in ("same", "valid", "pad"):
  327. return mode
  328. raise ValueError("The pad mode must be same or valid or pad,"" but got mode {}.".format(mode))
  329. def check_tensor_supported_type(dtype):
  330. """Check tensor dtype."""
  331. if dtype in (mstype.int32, mstype.float32):
  332. return dtype
  333. raise ValueError("The dtype must be mstype.int32 or mstype.float32, but got mstype {}.".format(dtype))
  334. def _expand_tuple(n_dimensions):
  335. """To expand a number to tuple."""
  336. def convert(m):
  337. if not isinstance(m, tuple):
  338. if isinstance(m, int):
  339. return tuple(repeat(m, n_dimensions))
  340. raise TypeError("Input type must be int or tuple.")
  341. if not len(m) is n_dimensions:
  342. raise TypeError("Input dimension is incorrect.")
  343. for i in m:
  344. if not isinstance(i, int):
  345. raise TypeError("Incorrect type inside of a tuple!")
  346. return m
  347. return convert
  348. def check_input_data(*data, data_class):
  349. """Input data check."""
  350. for item in data:
  351. if isinstance(item, (list, tuple)):
  352. for v in item:
  353. check_input_data(v, data_class=data_class)
  354. else:
  355. if not isinstance(item, data_class):
  356. raise ValueError(f'Please provide as model inputs'
  357. f' either a single'
  358. f' or a list of {data_class.__name__},'
  359. f' but got part data type is {str(type(item))}.')
  360. if item.size() == 0:
  361. msg = "Please provide non-empty data."
  362. logger.error(msg)
  363. raise ValueError(msg)
  364. def check_output_data(data):
  365. """Output data check."""
  366. if not data:
  367. raise RuntimeError('Executor return data ' + str(data) + ', please check your net or input data.')
  368. once = _expand_tuple(1)
  369. twice = _expand_tuple(2)
  370. triple = _expand_tuple(3)
  371. valid_data_types = (int, float, np.int8, np.int16, np.int32, np.int64,
  372. np.uint8, np.uint16, np.uint32, np.uint64, np.float16,
  373. np.float32, np.float64, bool, np.bool_)
  374. def check_type(arg_name, arg_value, valid_types):
  375. """Check value type."""
  376. # if input type is Tensor ,get element type
  377. if isinstance(arg_value, type(mstype.tensor)):
  378. arg_value = arg_value.element_type()
  379. # First, check if arg_value has argvalid_types
  380. if isinstance(arg_value, tuple(valid_types)):
  381. return type(arg_value).__name__
  382. # Second, wrap arg_value with numpy array so that it can be checked through numpy api
  383. if isinstance(arg_value, (list, tuple)):
  384. arg_value = np.array(arg_value)
  385. # Thirdly, check the data type by numpy's dtype api
  386. valid = False
  387. if isinstance(arg_value, np.ndarray):
  388. valid = arg_value.dtype in valid_data_types
  389. # Notice: bool is subclass of int, so `check_type('x', True, [int])` will check fail, and
  390. # `check_type('x', True, [bool, int])` will check pass
  391. if isinstance(arg_value, bool) and bool not in tuple(valid_types):
  392. valid = False
  393. if not valid:
  394. type_names = [t.__name__ for t in valid_types]
  395. if len(valid_types) == 1:
  396. raise TypeError(f'The type of `{arg_name}` should be {type_names[0]},'
  397. f' but got {type(arg_value).__name__}.')
  398. raise TypeError(f'The type of `{arg_name}` should be one of {type_names},'
  399. f' but got {type(arg_value).__name__}.')
  400. return type(arg_value).__name__
  401. def check_typename(arg_name, arg_type, valid_types):
  402. """Check type name."""
  403. def get_typename(t):
  404. return t.__name__ if hasattr(t, '__name__') else str(t)
  405. if isinstance(arg_type, type(mstype.tensor)):
  406. arg_type = arg_type.element_type()
  407. if arg_type in valid_types:
  408. return arg_type
  409. if isinstance(arg_type, tuple(valid_types)):
  410. return arg_type
  411. type_names = [get_typename(t) for t in valid_types]
  412. if len(valid_types) == 1:
  413. raise TypeError(f'The type of `{arg_name}` should be {type_names[0]},'
  414. f' but got {get_typename(arg_type)}.')
  415. raise TypeError(f'The type of `{arg_name}` should be one of {type_names},'
  416. f' but got {get_typename(arg_type)}.')
  417. def check_shape(arg_name, arg_value):
  418. """Check shape."""
  419. # First, check if shape is a tuple
  420. if not isinstance(arg_value, tuple):
  421. raise TypeError(f'The type of `{arg_name}` should be one of {tuple.__name__},'
  422. f' but got {type(arg_value).__name__}.')
  423. # Second, wrap arg_value with numpy array so that it can be checked through numpy api
  424. arg_value = np.array(arg_value)
  425. # shape can not be ()
  426. if arg_value.size == 0:
  427. raise ValueError('Shape can not be empty.')
  428. # shape's dimension should be 1
  429. if arg_value.ndim != 1:
  430. raise ValueError('Shape of tensor should be 1-dim vector, but got {}-dim.'.format(arg_value.ndim))
  431. # Thirdly, check each element's type of the shape
  432. valid_types = (int, np.int8, np.int16, np.int32, np.int64,
  433. np.uint8, np.uint16, np.uint32, np.uint64)
  434. for dim_size in arg_value:
  435. if not isinstance(dim_size, valid_types) or dim_size <= 0:
  436. raise ValueError('Every dimension size of the tensor shape should be a positive integer,'
  437. ' but got {}.'.format(dim_size))
  438. def _check_str_by_regular(target, reg=None, flag=re.ASCII):
  439. if reg is None:
  440. reg = _name_re
  441. if re.match(reg, target, flag) is None:
  442. raise ValueError("'{}' is illegal, it should be match regular'{}' by flags'{}'".format(target, reg, flag))
  443. return True
  444. def args_type_check(*type_args, **type_kwargs):
  445. """Check whether input data type is correct."""
  446. def type_check(func):
  447. sig = inspect.signature(func)
  448. bound_types = sig.bind_partial(*type_args, **type_kwargs).arguments
  449. @wraps(func)
  450. def wrapper(*args, **kwargs):
  451. nonlocal bound_types
  452. bound_values = sig.bind(*args, **kwargs)
  453. argument_dict = bound_values.arguments
  454. if "kwargs" in bound_types:
  455. bound_types = bound_types["kwargs"]
  456. if "kwargs" in argument_dict:
  457. argument_dict = argument_dict["kwargs"]
  458. for name, value in argument_dict.items():
  459. if name in bound_types:
  460. if value is not None and not isinstance(value, bound_types[name]):
  461. raise TypeError('Argument {} must be {}'.format(name, bound_types[name]))
  462. return func(*args, **kwargs)
  463. return wrapper
  464. return type_check