diff options
Diffstat (limited to 'stdnum/luhn.py')
-rw-r--r-- | stdnum/luhn.py | 37 |
1 files changed, 28 insertions, 9 deletions
diff --git a/stdnum/luhn.py b/stdnum/luhn.py index dbfb183..bc1b5ac 100644 --- a/stdnum/luhn.py +++ b/stdnum/luhn.py @@ -1,6 +1,6 @@ # luhn.py - functions for performing the Luhn and Luhn mod N algorithms # -# Copyright (C) 2010, 2011, 2012 Arthur de Jong +# Copyright (C) 2010, 2011, 2012, 2013 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public @@ -22,24 +22,30 @@ The Luhn algorithm is used to detect most accidental errors in various identification numbers. ->>> is_valid('7894') -False +>>> validate('7894') +Traceback (most recent call last): + ... +InvalidChecksum: ... >>> checksum('7894') 6 >>> calc_check_digit('7894') '9' ->>> is_valid('78949') -True +>>> validate('78949') +'78949' An alternative alphabet can be provided to use the Luhn mod N algorithm. The default alphabet is '0123456789'. ->>> is_valid('1234', alphabet='0123456789abcdef') -False +>>> validate('1234', alphabet='0123456789abcdef') +Traceback (most recent call last): + ... +InvalidChecksum: ... >>> checksum('1234', alphabet='0123456789abcdef') 14 """ +from stdnum.exceptions import * + def checksum(number, alphabet='0123456789'): """Calculate the Luhn checksum over the provided number. The checksum @@ -52,11 +58,24 @@ def checksum(number, alphabet='0123456789'): for i in number[1::2])) % n -def is_valid(number, alphabet='0123456789'): +def validate(number, alphabet='0123456789'): """Checks to see if the number provided passes the Luhn checksum.""" + if not bool(number): + raise InvalidFormat() try: - return bool(number) and checksum(number, alphabet) == 0 + valid = checksum(number, alphabet) == 0 except: + raise InvalidFormat() + if not valid: + raise InvalidChecksum() + return number + + +def is_valid(number, alphabet='0123456789'): + """Checks to see if the number provided passes the Luhn checksum.""" + try: + return bool(validate(number, alphabet)) + except ValidationError: return False |