#!/usr/bin/env python3 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. """Provides type checking for functions >>> @type_check ... def has_punctuation(test_string : str, punctuation="?!.") -> bool: ... for x in range(len(punctuation)): ... if punctuation[x] in test_string: ... return True ... return False >>> has_punctuation("The cow ran.") True >>> has_punctuation("Darn") False >>> has_punctuation(12) Traceback (most recent call last): ... TypeError: Argument 'test_string' expected type : received type """ __all__ = ['type_check'] __author__ = "Cody A. Taylor ( codemister99@yahoo.com )" __version__ = "0.3 alpha" import inspect, functools def type_check(function): """Check types if a type is provided in the annotations Works for both arguments and return annotations Does not require that all arguments have an annotation """ annotations = function.__annotations__ arg_spec = inspect.getfullargspec(function) @functools.wraps(function) def wrapper(*args, **kwargs): for name, arg in list(zip(arg_spec.args, args)) + list(kwargs.items()): try: if not isinstance(arg, annotations[name]): raise TypeError("Argument '{}' expected type {}: received type {}".format(name, annotations[name], type(arg))) except KeyError: pass #Ignore if a argument does not have an annotation result = function(*args, **kwargs) if "return" in annotations.keys() and not isinstance(result, annotations["return"]): raise TypeError("Retuen expected type {}: returned type {}".format(annotations["return"], type(result))) return result return wrapper @type_check def has_punctuation(test_string : str, punctuation="?!.") -> bool: """Example function for doctests Quick test if a character is in a string """ for x in range(len(punctuation)): if punctuation[x] in test_string: return True return False if __name__ == "__main__": import doctest doctest.testmod()