python-stdnum commit: r76 - in python-stdnum: . stdnum stdnum/br stdnum/iso7064 stdnum/nl stdnum/us
[
Date Prev][
Date Next]
[
Thread Prev][
Thread Next]
python-stdnum commit: r76 - in python-stdnum: . stdnum stdnum/br stdnum/iso7064 stdnum/nl stdnum/us
- From: Commits of the python-stdnum project <python-stdnum-commits [at] lists.arthurdejong.org>
- To: python-stdnum-commits [at] lists.arthurdejong.org
- Reply-to: python-stdnum-users [at] lists.arthurdejong.org
- Subject: python-stdnum commit: r76 - in python-stdnum: . stdnum stdnum/br stdnum/iso7064 stdnum/nl stdnum/us
- Date: Fri, 19 Aug 2011 10:22:16 +0200 (CEST)
Author: arthur
Date: Fri Aug 19 10:22:13 2011
New Revision: 76
URL: http://arthurdejong.org/viewvc/python-stdnum?view=rev&revision=76
Log:
make source code layout follow PEP8 more
Modified:
python-stdnum/getiban.py
python-stdnum/getisbn.py
python-stdnum/getisil.py
python-stdnum/setup.py
python-stdnum/stdnum/br/cpf.py
python-stdnum/stdnum/ean.py
python-stdnum/stdnum/grid.py
python-stdnum/stdnum/iban.py
python-stdnum/stdnum/imei.py
python-stdnum/stdnum/isan.py
python-stdnum/stdnum/isbn.py
python-stdnum/stdnum/isil.py
python-stdnum/stdnum/ismn.py
python-stdnum/stdnum/iso7064/mod_11_10.py
python-stdnum/stdnum/iso7064/mod_11_2.py
python-stdnum/stdnum/iso7064/mod_37_2.py
python-stdnum/stdnum/iso7064/mod_37_36.py
python-stdnum/stdnum/iso7064/mod_97_10.py
python-stdnum/stdnum/issn.py
python-stdnum/stdnum/luhn.py
python-stdnum/stdnum/meid.py
python-stdnum/stdnum/nl/bsn.py
python-stdnum/stdnum/numdb.py
python-stdnum/stdnum/us/ssn.py
python-stdnum/stdnum/verhoeff.py
Modified: python-stdnum/getiban.py
==============================================================================
--- python-stdnum/getiban.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/getiban.py Fri Aug 19 10:22:13 2011 (r76)
@@ -30,22 +30,26 @@
# The place where the current version of IBAN_Registry.txt can be downloaded.
download_url = 'http://www.swift.com/dsp/resources/documents/IBAN_Registry.txt'
+
def splitlines(f):
"""Read lines from the TAB-delimited IBAN_Registry.txt file and return
a dictionary per read line. We clean up the values a bit because it
contains some junk."""
stripit = ' \t\n\r;:\'"'
- firstline = [ x.strip(stripit) for x in f.readline().lower().split('\t') ]
+ firstline = [x.strip(stripit) for x in f.readline().lower().split('\t')]
for line in f:
- yield dict(zip(firstline, [ x.strip(stripit) for x in line.split('\t')
]))
+ yield dict(zip(firstline, [x.strip(stripit)
+ for x in line.split('\t')]))
+
def get_country_codes(line):
"""Return the list of country codes this line has."""
# simplest case first
if len(line['country code as defined in iso 3166']) == 2:
- return [ line['country code as defined in iso 3166'] ]
+ return [line['country code as defined in iso 3166']]
# fall back to parsing the IBAN structure
- return [ x.strip()[:2] for x in line['iban structure'].split(',') ]
+ return [x.strip()[:2] for x in line['iban structure'].split(',')]
+
def parse(f):
"""Parse the specified file."""
@@ -54,11 +58,14 @@
for line in splitlines(f):
for cc in get_country_codes(line):
# print country line
- print '%s country="%s" bban="%s"' % ( cc, line['name of country'],
line['bban structure'])
+ print '%s country="%s" bban="%s"' % (
+ cc, line['name of country'], line['bban structure'])
# TODO: some countries have a fixed check digit value
# TODO: some countries have extra check digits
# TODO: use "Bank identifier position within the BBAN" field
- # to add labels to the ranges (Bank identifier and Branch
Identifier)
+ # to add labels to the ranges (Bank identifier and Branch
+ # Identifier)
+
if __name__ == '__main__':
#f = open('IBAN_Registry.txt', 'r')
Modified: python-stdnum/getisbn.py
==============================================================================
--- python-stdnum/getisbn.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/getisbn.py Fri Aug 19 10:22:13 2011 (r76)
@@ -2,7 +2,7 @@
# getisbn.py - script to get ISBN prefix data
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -32,6 +32,7 @@
# The place where the current version of RangeMessage.xml can be downloaded.
download_url = 'http://www.isbn-international.org/agency?rmxml=1'
+
def _wrap(text):
"""Generator that returns lines of text that are no longer than
max_len."""
@@ -40,7 +41,7 @@
if i > 73:
i = text.rindex(',', 20, 73)
yield text[:i]
- text = text[i+1:]
+ text = text[i + 1:]
class RangeHandler(xml.sax.ContentHandler):
@@ -56,8 +57,8 @@
self._topranges = {}
def startElement(self, name, attrs):
- if name in ( 'MessageSerialNumber', 'MessageDate', 'Prefix',
- 'Agency', 'Range', 'Length', ):
+ if name in ('MessageSerialNumber', 'MessageDate', 'Prefix',
+ 'Agency', 'Range', 'Length'):
self._gather = ''
def characters(self, content):
@@ -78,18 +79,21 @@
elif name == 'Length':
self._length = int(self._gather.strip())
elif name == 'Rule' and self._length:
- self._ranges.append(tuple( x[:self._length] for x in
self._range.split('-') ))
+ self._ranges.append(tuple(x[:self._length]
+ for x in self._range.split('-')))
elif name == 'Rules':
if '-' in self._prefix:
p, a = self._prefix.split('-')
if p != self._last:
print p
self._last = p
- for line in _wrap(','.join(r[0] + '-' + r[1] for r in
self._topranges[p])):
- print ' %s' % ( line )
- print ' %s agency="%s"' % ( a, self._agency )
- for line in _wrap(','.join(r[0] + '-' + r[1] for r in
self._ranges)):
- print ' %s' % ( line )
+ for line in _wrap(','.join(r[0] + '-' + r[1]
+ for r in self._topranges[p])):
+ print ' %s' % line
+ print ' %s agency="%s"' % (a, self._agency)
+ for line in _wrap(','.join(r[0] + '-' + r[1]
+ for r in self._ranges)):
+ print ' %s' % line
else:
self._topranges[self._prefix] = self._ranges
self._ranges = []
Modified: python-stdnum/getisil.py
==============================================================================
--- python-stdnum/getisil.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/getisil.py Fri Aug 19 10:22:13 2011 (r76)
@@ -32,10 +32,12 @@
# the web page that holds information on the ISIL authorities
download_url = 'http://biblstandard.dk/isil/'
+
def clean(s):
"""Cleans up the string removing unneeded stuff from it."""
return spaces_re.sub(' ', s.replace(u'\u0096', '')).strip().encode('utf-8')
+
def parse(f):
"""Parse the specified file."""
print '# generated from ISIL Registration Authority, downloaded from'
@@ -57,8 +59,11 @@
elif tds[2].string:
props['ra'] = clean(tds[2].string)
# we could also get the search urls from tds[3].findAll('a')
- print '%s$ %s' % ( cc,
- ' '.join([ '%s="%s"' % (x, y) for x, y in props.iteritems()
]) )
+ print '%s$ %s' % (
+ cc,
+ ' '.join(['%s="%s"' % (x, y)
+ for x, y in props.iteritems()]))
+
if __name__ == '__main__':
#f = open('isil.html', 'r')
Modified: python-stdnum/setup.py
==============================================================================
--- python-stdnum/setup.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/setup.py Fri Aug 19 10:22:13 2011 (r76)
@@ -34,7 +34,7 @@
setup(name='python-stdnum',
version='0.5',
packages=find_packages(),
- package_data={ 'stdnum': ['*.dat'] },
+ package_data={'stdnum': ['*.dat']},
author='Arthur de Jong',
author_email='arthur@arthurdejong.org',
url='http://arthurdejong.org/python-stdnum',
Modified: python-stdnum/stdnum/br/cpf.py
==============================================================================
--- python-stdnum/stdnum/br/cpf.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/br/cpf.py Fri Aug 19 10:22:13 2011 (r76)
@@ -35,18 +35,18 @@
def compact(number):
"""Convert the number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
- number = number.replace(' ','').replace('-','').replace('.','').strip()
- # pad with leading zeroes
- return number
+ return number.replace(' ', '').replace('-', '').replace('.', '').strip()
+
def _calc_check_digits(number):
"""Calculate the check digits for the number."""
- d1 = sum( (10-i) * int(number[i]) for i in range(9) )
- d1 = ( 11 - d1 ) % 11 % 10
- d2 = sum( (11-i) * int(number[i]) for i in range(9) ) + 2 * d1
- d2 = ( 11 - d2 ) % 11 % 10
+ d1 = sum((10 - i) * int(number[i]) for i in range(9))
+ d1 = (11 - d1) % 11 % 10
+ d2 = sum((11 - i) * int(number[i]) for i in range(9)) + 2 * d1
+ d2 = (11 - d2) % 11 % 10
return '%d%d' % (d1, d2)
+
def is_valid(number):
"""Checks to see if the number provided is a valid BSN. This checks
the length and whether the check digit is correct."""
@@ -59,6 +59,7 @@
int(number) > 0 and \
_calc_check_digits(number) == number[-2:]
+
def format(number):
"""Reformat the passed number to the standard format."""
number = compact(number)
Modified: python-stdnum/stdnum/ean.py
==============================================================================
--- python-stdnum/stdnum/ean.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/ean.py Fri Aug 19 10:22:13 2011 (r76)
@@ -26,15 +26,19 @@
True
"""
+
def compact(number):
"""Convert the EAN to the minimal representation. This strips the number
of any valid separators and removes surrounding whitespace."""
- return number.replace(' ','').replace('-','').strip()
+ return number.replace(' ', '').replace('-', '').strip()
+
def calc_check_digit(number):
"""Calculate the EAN check digit for 13-digit numbers. The number passed
should not have the check bit included."""
- return str((10 - sum( (3 - 2 * (i % 2)) * int(n) for i, n in
enumerate(reversed(number)))) % 10)
+ return str((10 - sum((3 - 2 * (i % 2)) * int(n)
+ for i, n in enumerate(reversed(number)))) % 10)
+
def is_valid(number):
"""Checks to see if the number provided is a valid EAN-13. This checks
@@ -47,4 +51,3 @@
return len(number) in (13, 12, 8) and \
number.isdigit() and \
calc_check_digit(number[:-1]) == number[-1]
-
Modified: python-stdnum/stdnum/grid.py
==============================================================================
--- python-stdnum/stdnum/grid.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/grid.py Fri Aug 19 10:22:13 2011 (r76)
@@ -1,6 +1,6 @@
# grid.py - functions for handling Global Release Identifier (GRid) numbers
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -34,14 +34,16 @@
'A1-2425G-ABC1234002-M'
"""
+
def compact(number):
"""Convert the GRid to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
- number = number.replace(' ','').replace('-','').strip().upper()
+ number = number.replace(' ', '').replace('-', '').strip().upper()
if number.startswith('GRID:'):
number = number[5:]
return number
+
def is_valid(number):
"""Checks to see if the number provided is a valid GRid."""
from stdnum.iso7064 import mod_37_36
@@ -51,8 +53,9 @@
return False
return len(number) == 18 and mod_37_36.is_valid(number)
+
def format(number, separator='-', add_check_digit=False):
"""Reformat the passed number to the standard format."""
number = compact(number)
- number = ( number[0:2], number[2:7], number[7:17], number[17:] )
+ number = (number[0:2], number[2:7], number[7:17], number[17:])
return separator.join(x for x in number if x)
Modified: python-stdnum/stdnum/iban.py
==============================================================================
--- python-stdnum/stdnum/iban.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/iban.py Fri Aug 19 10:22:13 2011 (r76)
@@ -39,12 +39,18 @@
# our open copy of the IBAN database
_ibandb = numdb.get('iban')
+# the valid characters we have
+_alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+
+# regular expression to check IBAN structure
+_struct_re = re.compile('([1-9][0-9]*)!([nac])')
+
+
def compact(number):
"""Convert the iban number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
- return number.replace(' ','').replace('-','').strip().upper()
+ return number.replace(' ', '').replace('-', '').strip().upper()
-_alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def _convert(number):
"""Prepare the number to it's base10 representation (also moving the
@@ -53,8 +59,6 @@
# TODO: find out whether this should be in the mod_97_10 module
return ''.join(str(_alphabet.index(x)) for x in number[4:] + number[:4])
-# regular expression to check IBAN structure
-_struct_re = re.compile('([1-9][0-9]*)!([nac])')
def _matches_structure(number, structure):
"""Check the supplied number against the supplied structure."""
@@ -66,11 +70,12 @@
elif code == 'a' and not number[start:start + length].isalpha():
return False
elif code == 'c' and not number[start:start + length].isalnum():
- return False # should not happen due to checksum check
+ return False # should not happen due to checksum check
start += length
# the whole number should be parsed now
return start == len(number)
+
def is_valid(number):
"""Checks to see if the number provided is a valid IBAN."""
try:
@@ -85,7 +90,8 @@
# check if the number has the correct structure
return _matches_structure(number[4:], info[0][1].get('bban', ''))
+
def format(number, separator=' '):
"""Reformat the passed number to the space-separated format."""
number = compact(number)
- return separator.join(number[i:i+4] for i in range(0,len(number),4))
+ return separator.join(number[i:i + 4] for i in range(0, len(number), 4))
Modified: python-stdnum/stdnum/imei.py
==============================================================================
--- python-stdnum/stdnum/imei.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/imei.py Fri Aug 19 10:22:13 2011 (r76)
@@ -1,7 +1,7 @@
# imei.py - functions for handling International Mobile Equipment Identity
# (IMEI) numbers
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -39,8 +39,8 @@
def compact(number):
"""Convert the IMEI number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
- number = number.replace(' ','').replace('-','').strip().upper()
- return number
+ return number.replace(' ', '').replace('-', '').strip().upper()
+
def imei_type(number):
"""Check the passed number and returns 'IMEI', 'IMEISV' or None (for
@@ -49,9 +49,9 @@
number = compact(number)
except:
return None
- if len(number) == 14: # IMEI without check digit
+ if len(number) == 14: # IMEI without check digit
return 'IMEI' if number.isdigit() else None
- if len(number) == 15: # IMEI with check digit
+ if len(number) == 15: # IMEI with check digit
from stdnum import luhn
return 'IMEI' if luhn.is_valid(number) else None
elif len(number) == 16:
@@ -59,16 +59,18 @@
else:
return None
+
def is_valid(number):
"""Checks to see if the number provided is a valid IMEI (or IMEISV)
number."""
return imei_type(number) is not None
+
def format(number, separator='-', add_check_digit=False):
"""Reformat the passed number to the standard format."""
number = compact(number)
if len(number) == 14 and add_check_digit:
from stdnum import luhn
number += luhn.calc_check_digit(number)
- number = ( number[:2], number[2:8], number[8:14], number[14:] )
+ number = (number[:2], number[2:8], number[8:14], number[14:])
return separator.join(x for x in number if x)
Modified: python-stdnum/stdnum/isan.py
==============================================================================
--- python-stdnum/stdnum/isan.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/isan.py Fri Aug 19 10:22:13 2011 (r76)
@@ -1,7 +1,7 @@
# isan.py - functions for handling International Standard Audiovisual Numbers
# (ISANs)
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -46,13 +46,14 @@
"""Splits the number into a root, an episode or part, a check digit a
version and another check digit. If any of the parts are missing an
empty string is returned."""
- number = number.replace(' ','').replace('-','').strip().upper()
+ number = number.replace(' ', '').replace('-', '').strip().upper()
if len(number) == 17 or len(number) == 26:
- return ( number[0:12], number[12:16], number[16], number[17:25],
number[25:] )
+ return number[0:12], number[12:16], number[16], number[17:25],
number[25:]
elif len(number) > 16:
- return ( number[0:12], number[12:16], '', number[16:24], number[24:] )
+ return number[0:12], number[12:16], '', number[16:24], number[24:]
else:
- return ( number[0:12], number[12:16], number[16:], '', '' )
+ return number[0:12], number[12:16], number[16:], '', ''
+
def compact(number, strip_check_digits=True):
"""Convert the ISAN to the minimal representation. This strips the number
@@ -62,38 +63,41 @@
number[2] = number[4] = ''
return ''.join(number)
+
def _check(number, length, required=True):
- if ( number or required ) and length != len(number):
+ if (number or required) and length != len(number):
return False
for x in number:
if x not in '0123456789ABCDEF':
return False
return True
+
def is_valid(number):
"""Checks to see if the number provided is a valid ISAN. If check digits
are present in the number they are validated."""
try:
- ( root, episode, check1, version, check2 ) = split(number)
+ (root, episode, check1, version, check2) = split(number)
return _check(root, 12) and _check(episode, 4) and _check(version, 8,
False) \
- and ( not check1 or mod_37_36.is_valid(root+episode+check1) ) \
- and ( not check2 or mod_37_36.is_valid(root+episode+version+check2)
)
+ and (not check1 or mod_37_36.is_valid(root + episode + check1)) \
+ and (not check2 or mod_37_36.is_valid(root + episode + version +
check2))
except:
return False
+
def format(number, separator='-', strip_check_digits=False,
add_check_digits=True):
"""Reformat the passed number to the standard format. If
add_check_digits is True the check digit will be added if they are not
present yet. If both strip_check_digits and add_check_digits are True the
check digits will be recalculated."""
- ( root, episode, check1, version, check2 ) = split(number)
+ (root, episode, check1, version, check2) = split(number)
if strip_check_digits:
check1 = check2 = ''
if add_check_digits and not check1:
- check1 = mod_37_36.calc_check_digit(root+episode)
+ check1 = mod_37_36.calc_check_digit(root + episode)
if add_check_digits and not check2 and version:
- check2 = mod_37_36.calc_check_digit(root+episode+version)
- number = [ root[i:i+4] for i in range(0, 12, 4) ] + [ episode ]
+ check2 = mod_37_36.calc_check_digit(root + episode + version)
+ number = [root[i:i + 4] for i in range(0, 12, 4)] + [episode]
if check1:
number.append(check1)
if version:
@@ -102,16 +106,19 @@
number.append(check2)
return separator.join(number)
+
def to_binary(number):
"""Convert the number to it's binary representation (without the check
digits)."""
return compact(number, strip_check_digits=True).decode('hex')
+
def to_xml(number):
"""Returns the XML form of the ISAN as a string."""
number = format(number, strip_check_digits=True, add_check_digits=False)
return '<ISAN root="%s" episode="%s" version="%s" />' % (
- number[0:14], number[15:19], number[20:] )
+ number[0:14], number[15:19], number[20:])
+
def to_urn(number):
"""Returns the URN representation of the ISAN."""
Modified: python-stdnum/stdnum/isbn.py
==============================================================================
--- python-stdnum/stdnum/isbn.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/isbn.py Fri Aug 19 10:22:13 2011 (r76)
@@ -47,19 +47,22 @@
of any valid ISBN separators and removes surrounding whitespace. If the
covert parameter is True the number is also converted to ISBN-13
format."""
- number = number.replace(' ','').replace('-','').strip().upper()
+ number = number.replace(' ', '').replace('-', '').strip().upper()
if len(number) == 9:
number = '0' + number
if convert:
return to_isbn13(number)
return number
+
def _calc_isbn10_check_digit(number):
"""Calculate the ISBN check digit for 10-digit numbers. The number passed
should not have the check bit included."""
- check = sum( (i + 1) * int(n) for i, n in enumerate(number) ) % 11
+ check = sum((i + 1) * int(n)
+ for i, n in enumerate(number)) % 11
return 'X' if check == 10 else str(check)
+
def isbn_type(number):
"""Check the passed number and returns 'ISBN13', 'ISBN10' or None (for
invalid) for checking the type of number passed."""
@@ -82,6 +85,7 @@
else:
return None
+
def is_valid(number):
"""Checks to see if the number provided is a valid ISBN (either a legacy
10-digit one or a 13-digit one). This checks the length and the check
@@ -89,12 +93,13 @@
for that)."""
return isbn_type(number) is not None
+
def to_isbn13(number):
"""Convert the number to ISBN-13 format."""
number = number.strip()
min_number = compact(number)
if len(min_number) == 13:
- return number # nothing to do, already ISBN-13
+ return number # nothing to do, already ISBN-13
# put new check digit in place
number = number[:-1] + ean.calc_check_digit('978' + min_number[:-1])
# add prefix
@@ -105,6 +110,7 @@
else:
return '978' + number
+
def split(number, convert=False):
"""Split the specified ISBN into an EAN.UCC prefix, a group prefix, a
registrant, an item number and a check-digit. If the number is in ISBN-10
@@ -121,12 +127,13 @@
oprefix = prefix = number[:3]
number = number[3:]
# split the number
- result = numdb.get('isbn').split(prefix+number[:-1])[1:]
+ result = numdb.get('isbn').split(prefix + number[:-1])[1:]
itemnr = result.pop()
group = result.pop(0) if result else ''
publisher = result.pop(0) if result else ''
# return results
- return ( oprefix, group, publisher, itemnr, number[-1] )
+ return (oprefix, group, publisher, itemnr, number[-1])
+
def format(number, separator='-', convert=False):
"""Reformat the passed number to the standard format with the EAN.UCC
Modified: python-stdnum/stdnum/isil.py
==============================================================================
--- python-stdnum/stdnum/isil.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/isil.py Fri Aug 19 10:22:13 2011 (r76)
@@ -34,11 +34,13 @@
# the valid characters in an ISIL
_alphabet =
set('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-:/')
+
def compact(number):
"""Convert the ISIL to the minimal representation. This strips
surrounding whitespace."""
return number.strip()
+
def _known_agency(agency):
"""Checks whether the specified agency is valid."""
# look it up in the db
@@ -47,6 +49,7 @@
# there should be only one part and it should have properties
return len(results) == 1 and bool(results[0][1])
+
def is_valid(number):
"""Checks to see if the number provided is a valid isil (or isilSV)
number."""
@@ -59,6 +62,7 @@
return False
return len(number) <= 15 and _known_agency(number.split('-')[0])
+
def format(number):
"""Reformat the passed number to the standard format."""
number = compact(number)
Modified: python-stdnum/stdnum/ismn.py
==============================================================================
--- python-stdnum/stdnum/ismn.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/ismn.py Fri Aug 19 10:22:13 2011 (r76)
@@ -44,8 +44,9 @@
def compact(number):
"""Convert the ISMN to the minimal representation. This strips the number
of any valid ISMN separators and removes surrounding whitespace."""
- number = number.replace('
','').replace('-','').replace('.','').strip().upper()
- return number
+ number = number.replace(' ', '').replace('-', '').replace('.', '')
+ return number.strip().upper()
+
def is_valid(number):
"""Checks to see if the number provided is a valid ISMN (either a legacy
@@ -63,12 +64,13 @@
return True
return False
+
def to_ismn13(number):
"""Convert the number to ISMN13 format."""
number = number.strip()
min_number = compact(number)
if len(min_number) == 13:
- return number # nothing to do, already 13 digit format
+ return number # nothing to do, already 13 digit format
# add prefix and strip the M
if ' ' in number:
return '979 0' + number[1:]
@@ -78,8 +80,10 @@
return '9790' + number[1:]
# these are the ranges allocated to publisher codes
-_ranges = ( (3, '000', '099'), (4, '1000', '3999'), (5, '40000', '69999'),
- (6, '700000', '899999'), (7, '9000000', '9999999') )
+_ranges = (
+ (3, '000', '099'), (4, '1000', '3999'), (5, '40000', '69999'),
+ (6, '700000', '899999'), (7, '9000000', '9999999'))
+
def split(number):
"""Split the specified ISMN into a bookland prefix (979), an ISMN
@@ -89,8 +93,10 @@
number = to_ismn13(compact(number))
# rind the correct range and split the number
for length, low, high in _ranges:
- if low <= number[4:4+length] <= high:
- return number[:3], number[3], number[4:4+length],
number[4+length:-1], number[-1]
+ if low <= number[4:4 + length] <= high:
+ return (number[:3], number[3], number[4:4 + length],
+ number[4 + length:-1], number[-1])
+
def format(number, separator='-'):
"""Reformat the passed number to the standard format with the
Modified: python-stdnum/stdnum/iso7064/mod_11_10.py
==============================================================================
--- python-stdnum/stdnum/iso7064/mod_11_10.py Sat Jul 9 17:15:37 2011
(r75)
+++ python-stdnum/stdnum/iso7064/mod_11_10.py Fri Aug 19 10:22:13 2011
(r76)
@@ -1,6 +1,6 @@
# mod_11_10.py - functions for performing the ISO 7064 Mod 11, 10 algorithm
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -38,13 +38,15 @@
"""Calculate the checksum."""
check = 5
for n in number:
- check = ( ((check or 10) * 2) % 11 + int(n) ) % 10
+ check = (((check or 10) * 2) % 11 + int(n)) % 10
return check
+
def calc_check_digit(number):
"""With the provided number, calculate the extra digit that should be
appended to make it a valid number."""
- return str((1 - ( (checksum(number) or 10) * 2) % 11 ) % 10)
+ return str((1 - ((checksum(number) or 10) * 2) % 11) % 10)
+
def is_valid(number):
"""Checks whether the check digit is valid."""
Modified: python-stdnum/stdnum/iso7064/mod_11_2.py
==============================================================================
--- python-stdnum/stdnum/iso7064/mod_11_2.py Sat Jul 9 17:15:37 2011
(r75)
+++ python-stdnum/stdnum/iso7064/mod_11_2.py Fri Aug 19 10:22:13 2011
(r76)
@@ -1,6 +1,6 @@
# mod_11_2.py - functions for performing the ISO 7064 Mod 11, 2 algorithm
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -40,19 +40,20 @@
"""Calculate the checksum."""
check = 0
for n in number:
- check = ( 2 * check + int(10 if n == 'X' else n) ) % 11
+ check = (2 * check + int(10 if n == 'X' else n)) % 11
return check
+
def calc_check_digit(number):
"""With the provided number, calculate the extra digit that should be
appended to make it a valid number."""
- c = (1 - 2 * checksum(number) ) % 11
+ c = (1 - 2 * checksum(number)) % 11
return 'X' if c == 10 else str(c)
+
def is_valid(number):
"""Checks whether the check digit is valid."""
try:
return bool(number) and checksum(number) == 1
except:
return False
-
Modified: python-stdnum/stdnum/iso7064/mod_37_2.py
==============================================================================
--- python-stdnum/stdnum/iso7064/mod_37_2.py Sat Jul 9 17:15:37 2011
(r75)
+++ python-stdnum/stdnum/iso7064/mod_37_2.py Fri Aug 19 10:22:13 2011
(r76)
@@ -1,6 +1,6 @@
# mod_37_2.py - functions for performing the ISO 7064 Mod 37, 2 algorithm
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -47,14 +47,16 @@
modulus = len(alphabet)
check = 0
for n in number:
- check = ( 2 * check + alphabet.index(n) ) % modulus
+ check = (2 * check + alphabet.index(n)) % modulus
return check
+
def calc_check_digit(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*'):
"""With the provided number, calculate the extra digit that should be
appended to make it a valid number."""
modulus = len(alphabet)
- return alphabet[(1 - 2 * checksum(number, alphabet) ) % modulus]
+ return alphabet[(1 - 2 * checksum(number, alphabet)) % modulus]
+
def is_valid(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*'):
"""Checks whether the check digit is valid."""
Modified: python-stdnum/stdnum/iso7064/mod_37_36.py
==============================================================================
--- python-stdnum/stdnum/iso7064/mod_37_36.py Sat Jul 9 17:15:37 2011
(r75)
+++ python-stdnum/stdnum/iso7064/mod_37_36.py Fri Aug 19 10:22:13 2011
(r76)
@@ -1,6 +1,6 @@
# mod_37_36.py - functions for performing the ISO 7064 Mod 37, 36 algorithm
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -45,14 +45,16 @@
modulus = len(alphabet)
check = modulus / 2
for n in number:
- check = ( ((check or modulus) * 2) % (modulus + 1) + alphabet.index(n)
) % modulus
+ check = (((check or modulus) * 2) % (modulus + 1) + alphabet.index(n))
% modulus
return check
+
def calc_check_digit(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
"""With the provided number, calculate the extra digit that should be
appended to make it a valid number."""
modulus = len(alphabet)
- return alphabet[(1 - ( (checksum(number, alphabet) or modulus) * 2) %
(modulus + 1) ) % modulus]
+ return alphabet[(1 - ((checksum(number, alphabet) or modulus) * 2) %
(modulus + 1)) % modulus]
+
def is_valid(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
"""Checks whether the check digit is valid."""
Modified: python-stdnum/stdnum/iso7064/mod_97_10.py
==============================================================================
--- python-stdnum/stdnum/iso7064/mod_97_10.py Sat Jul 9 17:15:37 2011
(r75)
+++ python-stdnum/stdnum/iso7064/mod_97_10.py Fri Aug 19 10:22:13 2011
(r76)
@@ -1,6 +1,6 @@
# mod_97_10.py - functions for performing the ISO 7064 Mod 97, 10 algorithm
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -36,14 +36,17 @@
'35'
"""
+
def checksum(number):
"""Calculate the checksum."""
return int(number) % 97
+
def calc_check_digits(number):
"""With the provided number, calculate the extra digit that should be
appended to make it a valid number."""
- return '%02d' % (( 98 - 100 * checksum(number)) % 97)
+ return '%02d' % ((98 - 100 * checksum(number)) % 97)
+
def is_valid(number):
"""Determines whether the number has a valid checksum."""
Modified: python-stdnum/stdnum/issn.py
==============================================================================
--- python-stdnum/stdnum/issn.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/issn.py Fri Aug 19 10:22:13 2011 (r76)
@@ -1,6 +1,6 @@
# issn.py - functions for handling ISSNs
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -38,15 +38,17 @@
def compact(number):
"""Convert the ISSN to the minimal representation. This strips the number
of any valid ISSN separators and removes surrounding whitespace."""
- number = number.replace(' ','').replace('-','').strip().upper()
- return number
+ return number.replace(' ', '').replace('-', '').strip().upper()
+
def _calc_check_digit(number):
"""Calculate the ISSN check digit for 10-digit numbers. The number passed
should not have the check bit included."""
- check = (11 - sum( (8 - i) * int(n) for i, n in enumerate(number) ) ) % 11
+ check = (11 - sum((8 - i) * int(n)
+ for i, n in enumerate(number))) % 11
return 'X' if check == 10 else str(check)
+
def is_valid(number):
"""Checks to see if the number provided is a valid ISSN. This checks
the length and whether the check digit is correct."""
@@ -58,11 +60,13 @@
number[:-1].isdigit() and \
_calc_check_digit(number[:-1]) == number[-1]
+
def format(number):
"""Reformat the passed number to the standard format."""
number = compact(number)
return number[:4] + '-' + number[4:]
+
def to_ean(number, issue_code='00'):
"""Convert the number to EAN-13 format. The number is assumed to be a
valid ISSN."""
Modified: python-stdnum/stdnum/luhn.py
==============================================================================
--- python-stdnum/stdnum/luhn.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/luhn.py Fri Aug 19 10:22:13 2011 (r76)
@@ -1,6 +1,6 @@
# luhn.py - functions for performing the Luhn and Luhn mod N algorithms
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -48,9 +48,12 @@
"""Calculate the Luhn checksum over the provided number. The checksum
is returned as an int. Valid numbers should have a checksum of 0."""
n = len(alphabet)
- number = tuple( alphabet.index(i) for i in reversed(str(number)) )
- return ( sum(number[::2]) +
- sum( sum(divmod(i * 2, n)) for i in number[1::2] ) ) % n
+ number = tuple(alphabet.index(i)
+ for i in reversed(str(number)))
+ return (sum(number[::2]) +
+ sum(sum(divmod(i * 2, n))
+ for i in number[1::2])) % n
+
def is_valid(number, alphabet='0123456789'):
"""Checks to see if the number provided passes the Luhn checksum."""
@@ -59,6 +62,7 @@
except:
return False
+
def calc_check_digit(number, alphabet='0123456789'):
"""With the provided number, calculate the extra digit that should be
appended to make it pass the Luhn checksum."""
Modified: python-stdnum/stdnum/meid.py
==============================================================================
--- python-stdnum/stdnum/meid.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/meid.py Fri Aug 19 10:22:13 2011 (r76)
@@ -1,6 +1,6 @@
# meid.py - functions for handling Mobile Equipment Identifiers (MEIDs)
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -32,12 +32,14 @@
'AF 01 23 45 0A BC DE C'
"""
-_hex_alphabet='0123456789ABCDEF'
+_hex_alphabet = '0123456789ABCDEF'
+
def _cleanup(number):
"""Remove any grouping information from the number and removes surrounding
whitespace."""
- return str(number).replace(' ','').replace('-','').strip().upper()
+ return str(number).replace(' ', '').replace('-', '').strip().upper()
+
def _ishex(number):
for x in number:
@@ -45,23 +47,25 @@
return False
return True
+
def _parse(number):
number = _cleanup(number)
if len(number) == 14 and _ishex(number):
# 14-digit hex representation
- return ( number, '' )
+ return number, ''
elif len(number) == 15 and _ishex(number):
# 14-digit hex representation with check digit
- return ( number[0:14], number[14] )
+ return number[0:14], number[14]
elif len(number) == 18 and number.isdigit():
# 18-digit decimal representation
- return ( number, '' )
+ return number, ''
elif len(number) == 19 and number.isdigit():
# 18-digit decimal representation witch check digit
- return ( number[0:18], number[18] )
+ return number[0:18], number[18]
else:
return None
+
def _calc_check_digit(number):
# both the 18-digit decimal format and the 14-digit hex format
# containing only decimal digits should use the decimal Luhn check
@@ -71,6 +75,7 @@
else:
return luhn.calc_check_digit(number, alphabet=_hex_alphabet)
+
def compact(number, strip_check_digit=True):
"""Convert the MEID number to the minimal (hexadecimal) representation.
This strips grouping information, removes surrounding whitespace and
@@ -83,12 +88,13 @@
cd = ''
# convert to hex if needed
if len(number) == 18:
- number = '%08X%06X' % ( int(number[0:10]), int(number[10:18]) )
+ number = '%08X%06X' % (int(number[0:10]), int(number[10:18]))
if cd:
cd = _calc_check_digit(number)
# put parts back together again
return number + cd
+
def is_valid(number):
"""Checks to see if the number provided is a valid MEID number."""
from stdnum import luhn
@@ -107,6 +113,7 @@
# normal hex Luhn validation
return not cd or luhn.is_valid(number + cd, alphabet=_hex_alphabet)
+
def format(number, separator=' ', format=None, add_check_digit=False):
"""Reformat the passed number to the standard format. The separator
used can be provided. If the format is specified (either 'hex' or
@@ -118,12 +125,12 @@
# format conversions if needed
if format == 'dec' and len(number) == 14:
# convert to decimal
- number = '%010d%08d' % ( int(number[0:8], 16), int(number[8:14], 16) )
+ number = '%010d%08d' % (int(number[0:8], 16), int(number[8:14], 16))
if cd:
cd = _calc_check_digit(number)
elif format == 'hex' and len(number) == 18:
# convert to hex
- number = '%08X%06X' % ( int(number[0:10]), int(number[10:18]) )
+ number = '%08X%06X' % (int(number[0:10]), int(number[10:18]))
if cd:
cd = _calc_check_digit(number)
# see if we need to add a check digit
@@ -131,11 +138,13 @@
cd = _calc_check_digit(number)
# split number according to format
if len(number) == 14:
- number = [ number[i*2:i*2+2] for i in range(7) ] + [ cd ]
+ number = [number[i * 2:i * 2 + 2]
+ for i in range(7)] + [cd]
else:
- number = ( number[:5], number[5:10], number[10:14], number[14:], cd )
+ number = (number[:5], number[5:10], number[10:14], number[14:], cd)
return separator.join(x for x in number if x)
+
def to_pseudo_esn(number):
"""Convert the provided MEID to a pseudo ESN (pESN). The ESN is returned
in compact HEX representation."""
@@ -144,4 +153,4 @@
s = hashlib.sha1(compact(number, strip_check_digit=True).decode('hex'))
# return the last 6 digits of the hash prefixed with the reserved
# manufacturer code
- return "80" + s.hexdigest()[-6:].upper()
+ return '80' + s.hexdigest()[-6:].upper()
Modified: python-stdnum/stdnum/nl/bsn.py
==============================================================================
--- python-stdnum/stdnum/nl/bsn.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/nl/bsn.py Fri Aug 19 10:22:13 2011 (r76)
@@ -1,6 +1,6 @@
# bsn.py - functions for handling BSNs
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -34,13 +34,15 @@
def compact(number):
"""Convert the number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
- number = number.replace(' ','').replace('-','').replace('.','').strip()
+ number = number.replace(' ', '').replace('-', '').replace('.', '').strip()
# pad with leading zeroes
return (9 - len(number)) * '0' + number
+
def _calc_checksum(number):
"""Calculate the checksum over the number."""
- return sum( (9-i) * int(number[i]) for i in range(8) ) - int(number[8])
+ return sum((9 - i) * int(number[i]) for i in range(8)) - int(number[8])
+
def is_valid(number):
"""Checks to see if the number provided is a valid BSN. This checks
@@ -54,6 +56,7 @@
int(number) > 0 and \
_calc_checksum(number) % 11 == 0
+
def format(number):
"""Reformat the passed number to the standard format."""
number = compact(number)
Modified: python-stdnum/stdnum/numdb.py
==============================================================================
--- python-stdnum/stdnum/numdb.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/numdb.py Fri Aug 19 10:22:13 2011 (r76)
@@ -83,7 +83,8 @@
list (this is a generator)."""
# expand the results to all have the same length
ml = max(len(x) for x in results)
- results = [ x + (ml - len(x)) * [None] for x in results ]
+ results = [x + (ml - len(x)) * [None]
+ for x in results]
# go over each part
for parts in zip(*results):
# regroup parts into parts list and properties list
@@ -104,11 +105,11 @@
if prefixes:
for length, low, high, props, children in prefixes:
if low <= number[:length] <= high and len(number) >= length:
- results.append([ (number[:length], props) ] +
+ results.append([(number[:length], props)] +
NumDB._find(number[length:], children))
# not-found fallback
if not results:
- return [ ( number, {} ) ]
+ return [(number, {})]
# merge the results into a single result
return list(NumDB._merge(results))
@@ -142,13 +143,14 @@
low, high = rnge.split('-')
else:
low, high = rnge, rnge
- yield ( indent, len(low), low, high, props )
+ yield indent, len(low), low, high, props
+
def read(fp):
"""Return a new database with the data read from the specified file."""
last_indent = 0
db = NumDB()
- stack = { 0: db.prefixes }
+ stack = {0: db.prefixes}
for indent, length, low, high, props in _parse(fp):
if indent > last_indent:
# populate the children field of the last indent
@@ -159,6 +161,7 @@
last_indent = indent
return db
+
def get(name):
"""Opens a database with the specified name to perform queries on."""
if name not in _open_databases:
Modified: python-stdnum/stdnum/us/ssn.py
==============================================================================
--- python-stdnum/stdnum/us/ssn.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/us/ssn.py Fri Aug 19 10:22:13 2011 (r76)
@@ -38,13 +38,15 @@
_ssn_re =
re.compile('^(?P<area>[0-9]{3})-?(?P<group>[0-9]{2})-?(?P<serial>[0-9]{4})$')
# blacklist of SSNs
-_ssn_blacklist = set(( '078-05-1120', '457-55-5462', '219-09-9999' ))
+_ssn_blacklist = set(('078-05-1120', '457-55-5462', '219-09-9999'))
+
def compact(number):
"""Convert the number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
return number.replace('-', '').strip()
+
def is_valid(number):
"""Checks to see if the number provided is a valid SSN. This checks
the length, groups and formatting if it is present."""
@@ -65,6 +67,7 @@
# check blacklists
return format(number) not in _ssn_blacklist
+
def format(number):
"""Reformat the passed number to the standard format."""
if len(number) == 9:
Modified: python-stdnum/stdnum/verhoeff.py
==============================================================================
--- python-stdnum/stdnum/verhoeff.py Sat Jul 9 17:15:37 2011 (r75)
+++ python-stdnum/stdnum/verhoeff.py Fri Aug 19 10:22:13 2011 (r76)
@@ -1,6 +1,6 @@
# verhoeff.py - functions for performing the Verhoeff checksum
#
-# Copyright (C) 2010 Arthur de Jong
+# Copyright (C) 2010, 2011 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
@@ -38,38 +38,40 @@
# Verhoeff algorithm.
_multiplication_table = (
- [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
- [ 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 ],
- [ 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 ],
- [ 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 ],
- [ 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 ],
- [ 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 ],
- [ 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 ],
- [ 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 ],
- [ 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 ],
- [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ] )
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
+ [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
+ [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
+ [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
+ [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
+ [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
+ [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
+ [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
+ [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
+ [9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
_permutation_table = (
- ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
- ( 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 ),
- ( 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 ),
- ( 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 ),
- ( 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 ),
- ( 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 ),
- ( 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 ),
- ( 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 ) )
+ (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
+ (1, 5, 7, 6, 2, 8, 3, 0, 9, 4),
+ (5, 8, 0, 3, 7, 9, 6, 1, 4, 2),
+ (8, 9, 1, 6, 0, 4, 3, 5, 2, 7),
+ (9, 4, 5, 3, 1, 2, 6, 8, 7, 0),
+ (4, 2, 8, 6, 5, 7, 3, 9, 0, 1),
+ (2, 7, 9, 3, 8, 0, 6, 4, 1, 5),
+ (7, 0, 4, 6, 9, 1, 3, 2, 5, 8))
+
def checksum(number):
"""Calculate the Verhoeff checksum over the provided number. The checksum
is returned as an int. Valid numbers should have a checksum of 0."""
# transform number list
- number = tuple( int(n) for n in reversed(str(number)) )
+ number = tuple(int(n) for n in reversed(str(number)))
# calculate checksum
check = 0
for i, n in enumerate(number):
check = _multiplication_table[check][_permutation_table[i % 8][n]]
return check
+
def is_valid(number):
"""Checks to see if the number provided passes the Verhoeff checksum."""
try:
@@ -77,6 +79,7 @@
except:
return False
+
def calc_check_digit(number):
"""With the provided number, calculate the extra digit that should be
appended to make it pass the Verhoeff checksum."""
--
To unsubscribe send an email to
python-stdnum-commits-unsubscribe@lists.arthurdejong.org or see
http://lists.arthurdejong.org/python-stdnum-commits
- python-stdnum commit: r76 - in python-stdnum: . stdnum stdnum/br stdnum/iso7064 stdnum/nl stdnum/us,
Commits of the python-stdnum project