Skip to content

Instantly share code, notes, and snippets.

@blackrobot
Created February 25, 2015 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackrobot/e9e6ea43b39bac54453e to your computer and use it in GitHub Desktop.
Save blackrobot/e9e6ea43b39bac54453e to your computer and use it in GitHub Desktop.
def expand(cls, digits, number_system=0):
if len(digits) == cls.expected_length:
barcode = digits[1:-1]
number_system, checksum = digits[0], digits[-1]
elif len(digits) == cls.expected_length - 2:
barcode = digits
checksum = None
else:
raise ValueError("Invalid barcode length")
if barcode[-1] in '012':
upc = barcode[:2] + barcode[-1] + '0' * 4 + barcode[2:5]
elif barcode[-1] == '3':
upc = barcode[:3] + '0' * 5 + barcode[3:5]
elif barcode[-1] == '4':
upc = barcode[:4] + '0' * 5 + barcode[4]
else:
upc = barcode[:5] + '0' * 4 + barcode[-1]
upc_e = number_system + upc
check = UpcA.calc_check_digit(upc_e)
if checksum and checksum != check:
raise ValueError("Cannot expand, invalid UPC-E")
return UpcA(upc_e + check)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment