Elysia Tools
Navigation
Validation
UPC/EAN arithmetic with synthetic codes
Three runnable Python fixtures test check digits, rejection and leading zeros without assigning products or companies.
Samples
Entries inside this sample collection
Generate check digits
Run the generator for 7-, 11- and 12-digit synthetic bodies.
# Synthetic arithmetic fixtures only; no GS1 assignment or product claim.
def check_digit(body: str) -> str:
if len(body) not in (7, 11, 12) or not body.isascii() or not body.isdigit():
raise ValueError("Expected 7, 11 or 12 ASCII digits")
total = sum(int(c) * (3 if i % 2 == 0 else 1)
for i, c in enumerate(reversed(body)))
return str((-total) % 10)
def valid(code: str) -> bool:
return (len(code) in (8, 12, 13) and code.isascii() and code.isdigit()
and check_digit(code[:-1]) == code[-1])
bodies = ["0000001", "00000000001", "000000000001"]
codes = [body + check_digit(body) for body in bodies]
assert codes == ["00000017", "000000000017", "0000000000017"]
assert all(valid(code) for code in codes)
print([len(code) for code in codes]) # [8, 12, 13]
Reject altered controls
Run the validator against the original code, an altered check digit, a short string and a letter.
# Synthetic arithmetic fixtures only; no GS1 assignment or product claim.
def check_digit(body: str) -> str:
if len(body) not in (7, 11, 12) or not body.isascii() or not body.isdigit():
raise ValueError("Expected 7, 11 or 12 ASCII digits")
total = sum(int(c) * (3 if i % 2 == 0 else 1)
for i, c in enumerate(reversed(body)))
return str((-total) % 10)
def valid(code: str) -> bool:
return (len(code) in (8, 12, 13) and code.isascii() and code.isdigit()
and check_digit(code[:-1]) == code[-1])
good = "000000000017"
bad = good[:-1] + "8"
assert valid(good)
assert not valid(bad)
assert not valid("00000000001") # wrong complete-code length
assert not valid("00000000001A") # not ASCII digits
print("one valid code; three invalid controls")
Preserve leading zeros
Remove only ordinary display spaces, then compare string storage with integer conversion.
# Synthetic arithmetic fixtures only; no GS1 assignment or product claim.
def check_digit(body: str) -> str:
if len(body) not in (7, 11, 12) or not body.isascii() or not body.isdigit():
raise ValueError("Expected 7, 11 or 12 ASCII digits")
total = sum(int(c) * (3 if i % 2 == 0 else 1)
for i, c in enumerate(reversed(body)))
return str((-total) % 10)
def valid(code: str) -> bool:
return (len(code) in (8, 12, 13) and code.isascii() and code.isdigit()
and check_digit(code[:-1]) == code[-1])
display = "0000 0000 0017"
code = display.replace(" ", "") # explicitly allow ordinary spaces only
assert code == "000000000017" and valid(code)
assert len(code) == 12
assert str(int(code)) == "17"
assert not valid(str(int(code)))
print("keep identifiers as strings: 12 characters, not 2")
Tools
Tools frequently paired with this sample
Related
Related sample collections
Related