idstring 2.1.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- idstring/__init__.py +3 -0
- idstring/idstring.py +413 -0
- idstring-2.1.5.dist-info/METADATA +117 -0
- idstring-2.1.5.dist-info/RECORD +6 -0
- idstring-2.1.5.dist-info/WHEEL +5 -0
- idstring-2.1.5.dist-info/top_level.txt +1 -0
idstring/__init__.py
ADDED
idstring/idstring.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
""" A class defining a string of non-look-alike digits with a check digit, which can be incremented.
|
|
2
|
+
|
|
3
|
+
The intent is to create compact serial numbers using a defined alpha-numeric alphabet.
|
|
4
|
+
* a "host" field can be defined, so that, if the serial numbers are issued by a known set of
|
|
5
|
+
loosely cooperative units (think of couchdb hosts) the numbers will not conflict.
|
|
6
|
+
|
|
7
|
+
The default alphabet can be replaced by any unicode string you wish. The check digit will be from your alphabet.
|
|
8
|
+
|
|
9
|
+
The string is initialized using a five-argument call like; idstring.IDstring(IDstr, seed, host, seedstore, hash)
|
|
10
|
+
:IDstr an already-defined idstring.IDstring with checksum. [or None, if you are supplying a "seed"]
|
|
11
|
+
:seed - a "seed" value of valid idstring.ALPHABET characters with no checksum [ignored if IDstr is supplied]
|
|
12
|
+
:host - the identity number of the" host" on which it is running.
|
|
13
|
+
!!! NOTE: len(host) defines the size of the .host field !!!
|
|
14
|
+
:seedstore - a call-back function which the caller promises to use to preserve the state of the seed value.
|
|
15
|
+
- - - that function will be called with an idstring object so the caller can extract the incremented seed for storage.
|
|
16
|
+
- - - REMINDER...use the .value attribute or get_seed() method. The value of the IDstring cannot be incremented!
|
|
17
|
+
:hash - additional character(s) to alter the check digit, so that IDstrings for different purposes do not match.
|
|
18
|
+
- - - if hash is None, checksum generation and checking will be disabled.
|
|
19
|
+
:case_shift - function to apply to input strings. One of str.upper, str.lower, or None. Default is str.upper()
|
|
20
|
+
Copyright 2013, eHealth Africa http://www.ehealthafrica.org
|
|
21
|
+
Copyright 2022, Vernon Cole
|
|
22
|
+
|
|
23
|
+
"""
|
|
24
|
+
# This code is released and licensed under the terms of the Lesser GPL license as specified at the
|
|
25
|
+
# following URL:
|
|
26
|
+
# http://www.gnu.org/copyleft/lgpl.html
|
|
27
|
+
#
|
|
28
|
+
from collections.abc import Callable
|
|
29
|
+
import functools
|
|
30
|
+
|
|
31
|
+
__author__ = "Vernon Cole <vernondcole@gmail.com>"
|
|
32
|
+
__version__ = "2.1.5"
|
|
33
|
+
|
|
34
|
+
# -- a short calling sample -- real code would use a better storage method ---------
|
|
35
|
+
#- import pickle, idstring
|
|
36
|
+
#-
|
|
37
|
+
#- def my_seedstore(iDstr): # function to preserve the idString seed
|
|
38
|
+
#- global my_seed_memory
|
|
39
|
+
#- pkl_file = open('mySeedStore,pkl,'wb')
|
|
40
|
+
#- my_seed_memory['seed'] = iDstr.get_seed()
|
|
41
|
+
#- pickle.dump(my_seed_memory,pkl_file,-1)
|
|
42
|
+
#- pkl_file.close()
|
|
43
|
+
#-
|
|
44
|
+
#- # set up the idString for this run by retrieving it from storage
|
|
45
|
+
#- try: # retrieve the idString seed
|
|
46
|
+
#- pkl_file = open('mySeedStore.pkl','rb')
|
|
47
|
+
#- my_seed_memory = pickle.load(pkl_file)
|
|
48
|
+
#- pkl_file.close()
|
|
49
|
+
#- except:
|
|
50
|
+
#- # # the next statement would have been used to initialize the system & set the "host" number
|
|
51
|
+
#- my_seed_memory = {'host':'101','seed':'0000'} # initial value -- to be updated by pickle on later runs
|
|
52
|
+
#- raise Warning('Caution: IDstring storage not found -- your system may be broken')
|
|
53
|
+
#-
|
|
54
|
+
#- # initialize the idString factory with the saved values
|
|
55
|
+
#- present_id = idstring.IDstring(seed=my_seed_memory['seed'], host=my_seed_memory['host'], seedstore=my_seedstore)
|
|
56
|
+
#-
|
|
57
|
+
#- while I_am_still_working:
|
|
58
|
+
#- some_patient_data = some_kind_of_input()
|
|
59
|
+
#- present_id += 1 # generate a new patient number
|
|
60
|
+
#- print('Storing data for %s now...' % repr(present_id))
|
|
61
|
+
#- store_info(str(present_id), some_patient_data)
|
|
62
|
+
#-
|
|
63
|
+
#-----------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
class IdStringError(ValueError):
|
|
66
|
+
"""Base class for all errors in the IdString package"""
|
|
67
|
+
pass
|
|
68
|
+
class OutOfRangeError(IdStringError): pass
|
|
69
|
+
class InvalidIdError(IdStringError): pass
|
|
70
|
+
|
|
71
|
+
def noshift(s):
|
|
72
|
+
"""
|
|
73
|
+
a function which returns its argument unchanged (null)
|
|
74
|
+
"""
|
|
75
|
+
return s
|
|
76
|
+
|
|
77
|
+
DEFAULT_CASE_SHIFT = str.upper
|
|
78
|
+
|
|
79
|
+
_UNSET = object() # marks an argument which the caller did not supply
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class _class_or_instance_method:
|
|
83
|
+
"""like @classmethod, but the decorated function also receives the instance (or None if called on the class)"""
|
|
84
|
+
def __init__(self, func):
|
|
85
|
+
self.func = func
|
|
86
|
+
|
|
87
|
+
def __get__(self, instance, owner=None):
|
|
88
|
+
@functools.wraps(self.func)
|
|
89
|
+
def bound(*args, **kwargs):
|
|
90
|
+
return self.func(owner, instance, *args, **kwargs)
|
|
91
|
+
return bound
|
|
92
|
+
|
|
93
|
+
# define the characters which may legally appear in an idString
|
|
94
|
+
DEFAULT_ALPHABET = "0123456789ABCDEFGHJKLMNPRSTUVWXY"
|
|
95
|
+
|
|
96
|
+
# create a list of George Carlan's "the seven words you can't say on T.V."
|
|
97
|
+
# plus a few extras, but ignoring those with an "I" in them, since the default ALPHABET has no "I"
|
|
98
|
+
DEFAULT_DIRTY_WORDS = [c[::-1] for c in ['KCUF', 'TNUC', 'TRAF', 'DRUT', 'TAWT', 'SLLAB', 'SSA']]
|
|
99
|
+
DIRTY_I_WORDS = [c[::-1] for c in ['TIHS', 'TIT', 'SSIP']] # if your alternate alphabet contains an "I"
|
|
100
|
+
# alter your list like--> IDstring.DIRTY_WORDS = idstring.DEFAULT_DIRTY_WORDS + idstring.DIRTY_I_WORDS
|
|
101
|
+
# the words are stored backwards in the source, because 'kcuf' is not objectionable.
|
|
102
|
+
# the dirty word test is case independent.
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class IDstring(str):
|
|
106
|
+
"""
|
|
107
|
+
Returns a complex string-value object which has an _add_ method for plus 1.
|
|
108
|
+
"""
|
|
109
|
+
#the following are class attributes for IDstrings. They may be redefined if a programmer
|
|
110
|
+
#whishes to change what in "idString" looks like.
|
|
111
|
+
# For our sample application, We have chosen a three character hostNumber field and
|
|
112
|
+
# a four character idNumber field, with the default
|
|
113
|
+
# composed of a 32 character ALPHABET [0-9,A-H,J-N,P,R-Y]. i o q and z are out so no "1Il" "OQ0" "2Z" errors
|
|
114
|
+
# with a luhn_N check digit
|
|
115
|
+
ALPHABET = DEFAULT_ALPHABET
|
|
116
|
+
DIRTY_WORDS = DEFAULT_DIRTY_WORDS
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def thirty2(cls, *args):
|
|
120
|
+
raise NotImplementedError('This method has been deprecated.')
|
|
121
|
+
@classmethod
|
|
122
|
+
def thirty2int(cls, *args):
|
|
123
|
+
raise NotImplementedError('This method has been deprecated.')
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def __new__(cls, idstr=None, seed=None, host='', seedstore=None, hash='', alphabet=None,
|
|
128
|
+
case_shift=DEFAULT_CASE_SHIFT, no_check=False, context=None):
|
|
129
|
+
"""
|
|
130
|
+
:S - an existing legal idString, or None
|
|
131
|
+
:seed - the seed string for a new factory [ignored unless S is None]
|
|
132
|
+
:host - the host portion for a new idString factory, len(host) will set host length for factory
|
|
133
|
+
when cloning an existing IDstring, the host may be omitted (it is copied from the original)
|
|
134
|
+
:seedstore - a seed preservation function for the new factory
|
|
135
|
+
:context - a dictionary of things reserved for seedstore to use, internal to seedstore
|
|
136
|
+
(a new empty dictionary is created for each new factory if none is supplied)
|
|
137
|
+
:hash - an additional string to alter the calculation of the check digit for diverse projects
|
|
138
|
+
pass hash=None to turn off checksum testing and creation. Makes this module dumb.
|
|
139
|
+
:case_shift - function to apply to input strings. one of str.upper str.lower or None
|
|
140
|
+
"""
|
|
141
|
+
if case_shift is None:
|
|
142
|
+
case_shift = noshift
|
|
143
|
+
try:
|
|
144
|
+
if seed:
|
|
145
|
+
seed = case_shift(seed)
|
|
146
|
+
if host:
|
|
147
|
+
host = case_shift(host)
|
|
148
|
+
except TypeError:
|
|
149
|
+
raise InvalidIdError(f'Invalid seed "{seed}" or host "{host}" argument') from None
|
|
150
|
+
alphabet = alphabet or IDstring.ALPHABET
|
|
151
|
+
value = None
|
|
152
|
+
if isinstance(idstr, cls):
|
|
153
|
+
if not host: # host was not supplied, so keep the original's host
|
|
154
|
+
host = idstr.host
|
|
155
|
+
elif host != idstr.host:
|
|
156
|
+
raise InvalidIdError(f'Cannot use host "{host}" with id "{idstr}" (its host is "{idstr.host}")')
|
|
157
|
+
if seed is None: # making a clone
|
|
158
|
+
value = str(idstr)
|
|
159
|
+
seed = idstr._seed
|
|
160
|
+
hash = idstr.hash
|
|
161
|
+
alphabet = idstr.alphabet
|
|
162
|
+
seedstore = idstr.seedstore
|
|
163
|
+
case_shift = idstr.case_shift
|
|
164
|
+
context = idstr.context
|
|
165
|
+
elif isinstance(idstr, str):
|
|
166
|
+
us = case_shift(idstr) # if passing a string as on IDstring, it must already have a checksum
|
|
167
|
+
if no_check:
|
|
168
|
+
value = us
|
|
169
|
+
else:
|
|
170
|
+
if _sumcheck(us, hash, case_shift=case_shift, alphabet=alphabet):
|
|
171
|
+
value = us
|
|
172
|
+
else:
|
|
173
|
+
raise InvalidIdError(f'Invalid checksum in id={us}')
|
|
174
|
+
if value is None:
|
|
175
|
+
if isinstance(seed, str): # passing a seed means we need a checksum and host
|
|
176
|
+
new_root = seed + case_shift(host)
|
|
177
|
+
value = _checksum(new_root, hash, alphabet)
|
|
178
|
+
else:
|
|
179
|
+
raise InvalidIdError(f'No valid ID in id="{idstr}" or seed="{seed}"')
|
|
180
|
+
value = case_shift(value)
|
|
181
|
+
new = super().__new__(cls, value) #create the new instance
|
|
182
|
+
new._seed = seed # fill in the new instances attributes (as if we were __init__)
|
|
183
|
+
new.host = host
|
|
184
|
+
new.hash = hash
|
|
185
|
+
new.alphabet = alphabet
|
|
186
|
+
if seedstore is not None:
|
|
187
|
+
if not isinstance(seedstore, Callable):
|
|
188
|
+
raise IdStringError ('seedstore "%s" is not Callable' % repr(seedstore))
|
|
189
|
+
new.seedstore = seedstore
|
|
190
|
+
new.context = {} if context is None else context
|
|
191
|
+
new.case_shift = case_shift
|
|
192
|
+
return new
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def seed(self):
|
|
197
|
+
return self.get_seed()
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def get_seed(self):
|
|
201
|
+
"""extracts the incrementable part (without the host and checksum digits) of the IDstring"""
|
|
202
|
+
try:
|
|
203
|
+
stored_seed = self._seed
|
|
204
|
+
except AttributeError:
|
|
205
|
+
stored_seed = None
|
|
206
|
+
if stored_seed is None:
|
|
207
|
+
inc = 0 if self.hash is None else 1
|
|
208
|
+
try:
|
|
209
|
+
n = len(self.host) + inc
|
|
210
|
+
except TypeError:
|
|
211
|
+
n = inc
|
|
212
|
+
ret = str(self)[:-n] if n > 0 else str(self)
|
|
213
|
+
self._seed = ret # cache for next time
|
|
214
|
+
return ret
|
|
215
|
+
return stored_seed
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _next_value(self):
|
|
219
|
+
"""create the next sequential idString"""
|
|
220
|
+
cat = ''
|
|
221
|
+
seed = self.get_seed()
|
|
222
|
+
n = len(seed)
|
|
223
|
+
keep_looping = True
|
|
224
|
+
while keep_looping: # this is done using string math (not binary) since usually only one digit is changed
|
|
225
|
+
n -= 1
|
|
226
|
+
c = seed[n]
|
|
227
|
+
i = self.alphabet.find(c)
|
|
228
|
+
try:
|
|
229
|
+
cat = self.alphabet[i+1] + cat # attempt to get the next higher character on the ALPHABET string
|
|
230
|
+
keep_looping = False # if successful, no carry is needed
|
|
231
|
+
except IndexError: # a carry is needed, will keep looping
|
|
232
|
+
cat = self.alphabet[0] + cat # supply the lowest character on the ALPHABET string
|
|
233
|
+
if n == 0: # carrying out of the most significant digit
|
|
234
|
+
carry_digit = '1' if self.alphabet[0] == '0' else self.alphabet[0]
|
|
235
|
+
cat = carry_digit + cat # add a new place
|
|
236
|
+
keep_looping = False
|
|
237
|
+
seed = seed[:n] + cat
|
|
238
|
+
self._seed = seed
|
|
239
|
+
return _checksum(seed + self.host, self.hash, self.alphabet)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _run_factory(self):
|
|
243
|
+
"""increments the IDstring, skipping evil words
|
|
244
|
+
<<CAUTION: increments next_value but DOES NOT CHANGE self.__str__>>"""
|
|
245
|
+
next_value = self._next_value()
|
|
246
|
+
# now make sure we're not printing an "unprintable" word
|
|
247
|
+
checksum_size = 1 if self.hash is not None else 0
|
|
248
|
+
next_upped = next_value.upper()
|
|
249
|
+
for bad_word in self.DIRTY_WORDS:
|
|
250
|
+
if bad_word in next_upped:
|
|
251
|
+
wherebad = next_upped.find(bad_word) + len(bad_word)
|
|
252
|
+
try: staticlen = len(self.host) + checksum_size
|
|
253
|
+
except AttributeError: staticlen = 1
|
|
254
|
+
wherebad = min(len(next_value) - staticlen, wherebad) - checksum_size # change the seed, not the checksum character itself
|
|
255
|
+
c = next_value[wherebad] # find the digit for last changeable letter of the bad word
|
|
256
|
+
next_index = self.alphabet.find(c) + 1 # and increment it
|
|
257
|
+
if next_index < len(self.alphabet): # if the bad word does not end in 'Y'
|
|
258
|
+
next_root = next_value[:wherebad] + self.alphabet[next_index] + next_value[wherebad+1:-1]
|
|
259
|
+
next_value = _checksum(next_root, self.hash, self.alphabet)
|
|
260
|
+
else:
|
|
261
|
+
next_value = self._run_factory() # will this ever happen?
|
|
262
|
+
del self._seed # invalidate cached seed
|
|
263
|
+
return next_value
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def __add__(self, other):
|
|
267
|
+
"""supports 'IDstring + 1' to generate the next serial number. (all other addends just do str concat)
|
|
268
|
+
|
|
269
|
+
if idstring.host was defined, skip that many characters before incrementing
|
|
270
|
+
if seedstore() returns a value (other than None) that will become the new incremented value
|
|
271
|
+
"""
|
|
272
|
+
if other == 1:
|
|
273
|
+
next_thing = self._run_factory()
|
|
274
|
+
# Python strings are immutable, so we must create a new instance
|
|
275
|
+
ret = IDstring(next_thing, host=self.host, seedstore=self.seedstore, hash=self.hash,
|
|
276
|
+
case_shift=self.case_shift, alphabet=self.alphabet, no_check=True, context=self.context)
|
|
277
|
+
if ret.seedstore: # call the seedstore function supplied by the program, with "self" as an argument
|
|
278
|
+
correction = ret.seedstore(ret)
|
|
279
|
+
if correction: # user can return a new, improved ID value
|
|
280
|
+
return correction
|
|
281
|
+
return ret
|
|
282
|
+
else:
|
|
283
|
+
return str(self) + other
|
|
284
|
+
|
|
285
|
+
@property
|
|
286
|
+
def value(self):
|
|
287
|
+
return str(self)
|
|
288
|
+
|
|
289
|
+
def __repr__(self):
|
|
290
|
+
return "idString('%s')" % str(self) # reveal what's inside
|
|
291
|
+
|
|
292
|
+
@classmethod
|
|
293
|
+
def checksum(cls, s, hash='', alphabet=''):
|
|
294
|
+
alphabet = alphabet or cls.ALPHABET
|
|
295
|
+
return _checksum(s, hash, alphabet)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
@_class_or_instance_method
|
|
299
|
+
def sumcheck(cls, self, s=None, hash=_UNSET, alphabet=_UNSET, case_shift=_UNSET):
|
|
300
|
+
"""True if the checksum of s is valid.
|
|
301
|
+
|
|
302
|
+
IDstring.sumcheck('TESTME2K') checks a string using the default (or supplied) hash, alphabet and case_shift.
|
|
303
|
+
my_id.sumcheck() checks my_id itself, using its own hash, alphabet and case_shift
|
|
304
|
+
(unless they are supplied as arguments).
|
|
305
|
+
"""
|
|
306
|
+
if s is None and self is not None: # called as an instance method: check this instance
|
|
307
|
+
s = str(self)
|
|
308
|
+
hash = self.hash if hash is _UNSET else hash
|
|
309
|
+
alphabet = self.alphabet if alphabet is _UNSET else alphabet
|
|
310
|
+
case_shift = self.case_shift if case_shift is _UNSET else case_shift
|
|
311
|
+
if s is None:
|
|
312
|
+
raise TypeError('sumcheck() needs a string to check when called on the class')
|
|
313
|
+
hash = '' if hash is _UNSET else hash
|
|
314
|
+
alphabet = None if alphabet is _UNSET else alphabet
|
|
315
|
+
case_shift = None if case_shift is _UNSET else case_shift
|
|
316
|
+
return _sumcheck(s, hash, alphabet, case_shift)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
# checksum calulations ...
|
|
320
|
+
# calculate a check digit using an arbitrary ALPHABET
|
|
321
|
+
# using
|
|
322
|
+
# the Luhn mod N algorithm from http://en.wikipedia.org/wiki/Luhn_mod_N_algorithm retrieved 10-1-2013
|
|
323
|
+
# original code from wikipedia is identified by the #w comment marks
|
|
324
|
+
#w
|
|
325
|
+
#w Assuming the following functions are defined:
|
|
326
|
+
#w
|
|
327
|
+
#w function int CodePointFromCharacter(char character) {...}
|
|
328
|
+
#w
|
|
329
|
+
#w function char CharacterFromCodePoint(int codePoint) {...}
|
|
330
|
+
#w
|
|
331
|
+
#w function int NumberOfValidInputCharacters() {...}
|
|
332
|
+
#w
|
|
333
|
+
#w The function to generate a check character is:
|
|
334
|
+
#w
|
|
335
|
+
#w function char GenerateCheckCharacter(string s) {
|
|
336
|
+
def _checksum(s, hash='', alphabet=''): #w
|
|
337
|
+
"""idstring.checksum('s': string) --> s string with checksum appended"""
|
|
338
|
+
if hash is None:
|
|
339
|
+
return s
|
|
340
|
+
instr = s + hash # append the hash string to make unique calculations
|
|
341
|
+
factor = 2 #w int factor = 2;
|
|
342
|
+
sum = 0 #w int sum = 0;
|
|
343
|
+
n = len(alphabet) #w int n = NumberOfValidInputCharacters();
|
|
344
|
+
#w
|
|
345
|
+
#w // Starting from the right and working leftwards is easier since
|
|
346
|
+
#w // the initial "factor" will always be "2"
|
|
347
|
+
#w for (int i = input.Length - 1; i >= 0; i--) {
|
|
348
|
+
for c in instr[::-1]:
|
|
349
|
+
codePoint = alphabet.find(c) #w int codePoint = CodePointFromCharacter(input[i]);
|
|
350
|
+
addend = factor * codePoint #w int addend = factor * codePoint;
|
|
351
|
+
#w
|
|
352
|
+
#w// Alternate the "factor" that each "codePoint" is multiplied by
|
|
353
|
+
factor = 1 if factor == 2 else 2 #w factor = (factor == 2) ? 1 : 2;
|
|
354
|
+
#w
|
|
355
|
+
#w// Sum the digits of the "addend" as expressed in base "n"
|
|
356
|
+
addend = (addend // n) + (addend % n) #w addend = (addend / n) + (addend % n);
|
|
357
|
+
sum += addend #w sum += addend;
|
|
358
|
+
#w}
|
|
359
|
+
#w// Calculate the number that must be added to the "sum"
|
|
360
|
+
#w // to make it divisible by "n"
|
|
361
|
+
remainder = sum % n #w int remainder = sum % n;
|
|
362
|
+
checkCodePoint = (n - remainder) % n #w int checkCodePoint = (n - remainder) % n;
|
|
363
|
+
#w
|
|
364
|
+
# (we return the entire checksummed string, not just the checksum character)
|
|
365
|
+
return s + alphabet[checkCodePoint] #w return CharacterFromCodePoint(checkCodePoint);
|
|
366
|
+
|
|
367
|
+
#w}
|
|
368
|
+
#w
|
|
369
|
+
#w And the function to validate a string (with the check character as the last character) is:
|
|
370
|
+
#w
|
|
371
|
+
#w function bool ValidateCheckCharacter(string input) {
|
|
372
|
+
def _sumcheck(s, hash='', alphabet=None, case_shift=None):
|
|
373
|
+
"""idstring.sumcheck(S: IDSTRING) --> True is checksum is valid"""
|
|
374
|
+
if not alphabet:
|
|
375
|
+
alphabet = IDstring.ALPHABET
|
|
376
|
+
if case_shift is None:
|
|
377
|
+
case_shift = DEFAULT_CASE_SHIFT
|
|
378
|
+
if hash is None: # if checksums are not in use. . .
|
|
379
|
+
for c in case_shift(s): # just check for valid characters
|
|
380
|
+
if c not in alphabet:
|
|
381
|
+
return False
|
|
382
|
+
return True
|
|
383
|
+
|
|
384
|
+
factor = 1 #w int factor = 1;
|
|
385
|
+
sum = 0 #w int sum = 0;
|
|
386
|
+
n = len(alphabet) #w int n = NumberOfValidInputCharacters();
|
|
387
|
+
s_hash = s[:-1] + str(hash) + s[-1] # if len(s) > 1 else s + str(hash) # place hash characters next-to right
|
|
388
|
+
instr = case_shift(s_hash)
|
|
389
|
+
|
|
390
|
+
# optional "hash" is used to create unique check digits for various projects
|
|
391
|
+
#w
|
|
392
|
+
#w// Starting from the right, work leftwards
|
|
393
|
+
#w// Now, the initial "factor" will always be "1"
|
|
394
|
+
#w// since the last character is the check character
|
|
395
|
+
try:
|
|
396
|
+
for c in instr[::-1]: #w for (int i = input.Length - 1; i >= 0; i--) {
|
|
397
|
+
codePoint = alphabet.find(c) #w int codePoint = CodePointFromCharacter(input[i]);
|
|
398
|
+
addend = factor * codePoint #w int addend = factor * codePoint;
|
|
399
|
+
#w
|
|
400
|
+
#w// Alternate the "factor" that each "codePoint" is multiplied by
|
|
401
|
+
factor = 1 if factor == 2 else 2 #w factor = (factor == 2) ? 1 : 2;
|
|
402
|
+
#w
|
|
403
|
+
#w// Sum the digits of the "addend" as expressed in base "n"
|
|
404
|
+
addend = (addend // n) + (addend % n) #w addend = (addend / n) + (addend % n);
|
|
405
|
+
sum += addend #w sum += addend;
|
|
406
|
+
#w}
|
|
407
|
+
except (ValueError, TypeError):
|
|
408
|
+
return False
|
|
409
|
+
remainder = sum % n #w int remainder = sum % n;
|
|
410
|
+
#w
|
|
411
|
+
return remainder == 0 #w return (remainder == 0);
|
|
412
|
+
#w}
|
|
413
|
+
#----end of <idstring.py> --------------------------------------------------------
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: idstring
|
|
3
|
+
Version: 2.1.5
|
|
4
|
+
Summary: A Python package to create unique, checksummed serial-number strings.
|
|
5
|
+
Author: Vernon Cole
|
|
6
|
+
Author-email: vernondcole@gmail.com
|
|
7
|
+
Project-URL: repository, https://github.com/vernondcole/idstring
|
|
8
|
+
Project-URL: documentation, https://github.com/vernondcole/idstring/wiki
|
|
9
|
+
Keywords: serial number,string,checksum,Luhn,increment
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: GNU General Public License (GPL)
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Natural Language :: English
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Topic :: Software Development
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
idstring
|
|
22
|
+
========
|
|
23
|
+
|
|
24
|
+
Python module to create alpha-numeric serial number strings with a check digit, with smart incrementing.
|
|
25
|
+
|
|
26
|
+
an IDstring is a string-like object which can be incremented, to produce
|
|
27
|
+
a series of serial-number-like strings, consisting of Arabic digits and upper case letters,
|
|
28
|
+
skipping those which can be easily misinterpreted ("oh", "I", "Q", and Zed) and which has
|
|
29
|
+
(by defaut) an optional Luhn-N check digit, capable of detecting any single-letter error and most other errors.
|
|
30
|
+
|
|
31
|
+
Programmers may define alternate alphabets, alternate lists of "dirty" words (which are skipped),
|
|
32
|
+
a fixed subfield for generating serial number from multiple sources, and a hash code to create unique check
|
|
33
|
+
digits algorithms for multiple projects. Passing a hash code of None will surpress check digit operation.
|
|
34
|
+
|
|
35
|
+
For more explanation, please refer to [the wiki on github](https://github.com/vernondcole/idstring/wiki)
|
|
36
|
+
|
|
37
|
+
class IDstring generates (and checks) alphanumeric serial number strings with a checksum
|
|
38
|
+
|
|
39
|
+
### changes:
|
|
40
|
+
|
|
41
|
+
* 2018 Update: Still works fine in Python 3.6. No issues have been filed, no bugs reported.
|
|
42
|
+
|
|
43
|
+
* 2022 Update: works with Python 3.10. Python 2.7 dropped. Version 2.0.1
|
|
44
|
+
|
|
45
|
+
* Version 2.0:
|
|
46
|
+
* Added ability to pass hash=None to turn off checksums.
|
|
47
|
+
* Support for lower-case letters in alphabets.
|
|
48
|
+
* Assigning alternate alphabets (etc.) during instance creation.
|
|
49
|
+
* Choice of automatic case shift upper, lower, or None.
|
|
50
|
+
* Some small breaking changes. Especially . . .
|
|
51
|
+
* The use of IdString(seed='sss') syntax is required in usual cases when manually creating a new instance.
|
|
52
|
+
* The wonky 5-bit binary conversion functions, which only worked with the default alphabet, have been removed.
|
|
53
|
+
* Version 2.1:
|
|
54
|
+
* adds a .context dictionary to the IDstring object which a seedstore method can use to store its operating context.
|
|
55
|
+
* Version 2.1.5:
|
|
56
|
+
* Requires Python 3.11 or newer. (Users of older Pythons will continue to get version 2.1.4.)
|
|
57
|
+
* Bug fixes: the .value property now returns the string; IDstring(existing_id) copies the host of an id which has one;
|
|
58
|
+
my_id.sumcheck() checks the instance using its own hash, alphabet and case_shift;
|
|
59
|
+
each new IDstring factory gets its own .context dictionary (they had been sharing one).
|
|
60
|
+
* Tests now run automatically on GitHub Actions for every pull request.
|
|
61
|
+
|
|
62
|
+
### operation:
|
|
63
|
+
IDstring extends the built-in str class, using an __ADD__ method which accepts the integer ONE.
|
|
64
|
+
Adding 1 to an instance of the class will generate a new instance with an incremented value (and a new checksum).
|
|
65
|
+
|
|
66
|
+
So, in short, you can generate serial numbers like this:
|
|
67
|
+
|
|
68
|
+
serial = idstring.IDstring(seed='1Y3R9C')
|
|
69
|
+
while serial.startswith('1'): # notice that it is like a string, so .startswith works.
|
|
70
|
+
serial += 1 # Increments the string & generates a new checksum.
|
|
71
|
+
print(serial)
|
|
72
|
+
|
|
73
|
+
Starting from "1Y3R9CB" (the seed plus its check digit), the loop runs 925,387 times, ending with:
|
|
74
|
+
```
|
|
75
|
+
1YYYYVA
|
|
76
|
+
1YYYYW8
|
|
77
|
+
1YYYYX6
|
|
78
|
+
1YYYYY4
|
|
79
|
+
200000X
|
|
80
|
+
```
|
|
81
|
+
Incrementation flows smoothly through the alphabet -- "9" increments to "A". Incrementing "Y" gives "0" and
|
|
82
|
+
causes a carry to increment the next digit. If you run out of digits, a "1" is prepended to the string.
|
|
83
|
+
(By default. Alternate alphabets increment in their implied order.
|
|
84
|
+
The actual code for a new leading digit is: "carry_digit = '1' if self.alphabet[0] == '0' else self.alphabet[0]")
|
|
85
|
+
|
|
86
|
+
The "Luhn mod N" algorithm is used (unless disabled) to add another digit (from the same alphabet) as a check digit.
|
|
87
|
+
|
|
88
|
+
The routine will automatically skip over patterns which contain substrings matching a list of "Dirty Words."
|
|
89
|
+
Without that filter, the above example would have produced 925,396 results; the filter skipped 9 objectionable values.
|
|
90
|
+
|
|
91
|
+
You can override the supplied alphabet and objectionable word lists. Alternate alphabets overflow correctly.
|
|
92
|
+
|
|
93
|
+
You may supply an optional call-back function to assist in maintaining the persistence of the serial number
|
|
94
|
+
sequence of multiple program runs.
|
|
95
|
+
|
|
96
|
+
The Luhn-N check digit will detect any single character substitution, any inversion of adjacent characters
|
|
97
|
+
(except the first and last character in the alphabet: i.e. 0<->Y for the supplied default) and most other errors.
|
|
98
|
+
|
|
99
|
+
The default alphabet consists of [0-9] and [A-Y] dropping "I", "O", and "Q".
|
|
100
|
+
|
|
101
|
+
Provision is made for a fixed subfield (of user defined length) between the check digit and the incrementing
|
|
102
|
+
field, so that multiple sites can produce non-overlapping series of numbers. This subfield and the check digit
|
|
103
|
+
are included in the "dirty word" checking.
|
|
104
|
+
|
|
105
|
+
### still don't understand?
|
|
106
|
+
Read the source, Luke.
|
|
107
|
+
https://pypi.org/project/idstring/#files
|
|
108
|
+
|
|
109
|
+
Read (and then test run) the program sample_seedstore.py to see how it works.
|
|
110
|
+
|
|
111
|
+
Run "python sample_seedstore.py" from multiple terminals to observe how it uses
|
|
112
|
+
a one-row SQL database to maintain the seed value and gives unique values.
|
|
113
|
+
|
|
114
|
+
### installation:
|
|
115
|
+
Installation uses the usual Python methods:
|
|
116
|
+
|
|
117
|
+
pip install idstring
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
idstring/__init__.py,sha256=CmbNg9sC9FOSzTfNPgyh8FzWV8liKnBoVd809VIxjn4,182
|
|
2
|
+
idstring/idstring.py,sha256=QrTs4PmFDV-QrPjgJyDgLdpYurYee_-gPDaaJDoXUl8,19909
|
|
3
|
+
idstring-2.1.5.dist-info/METADATA,sha256=9ygqoqMpX-OazEKm-QNmyG6zqbfTQ9SglBXVUlZVomc,5807
|
|
4
|
+
idstring-2.1.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
idstring-2.1.5.dist-info/top_level.txt,sha256=YBida-fXFwoRhU66QGWXSSa8jbhxxi8kn9ZChM4_ac8,9
|
|
6
|
+
idstring-2.1.5.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
idstring
|