Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file modified barcode/__init__.py
100755 → 100644
Empty file.
10 changes: 8 additions & 2 deletions barcode/base.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
if TYPE_CHECKING:
from typing import BinaryIO

from PIL.Image import Image as T_Image


class Barcode:
name = ""
Expand Down Expand Up @@ -53,7 +55,7 @@ def build(self) -> list[str]:
other characters such as G for guard lines (e.g. in EAN13)."""
raise NotImplementedError

def get_fullcode(self):
def get_fullcode(self) -> str:
"""Returns the full code, encoded in the barcode.

:returns: Full human readable code.
Expand Down Expand Up @@ -92,7 +94,11 @@ def write(
output = self.render(options, text)
self.writer.write(output, fp)

def render(self, writer_options: dict | None = None, text: str | None = None):
def render(
self,
writer_options: dict | None = None,
text: str | None = None,
) -> bytes | T_Image:
"""Renders the barcode using `self.writer`.

:param writer_options: Options for `self.writer`, see writer docs for details.
Expand Down
2 changes: 1 addition & 1 deletion barcode/charsets/code39.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,4 @@
MIDDLE = "0"

# MAP for assigning every symbol (REF) to (reference number, barcode)
MAP = dict(zip(REF, enumerate(CODES)))
MAP = dict(zip(REF, enumerate(CODES), strict=True))
15 changes: 13 additions & 2 deletions barcode/codabar.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,16 @@

__docformat__ = "restructuredtext en"

from typing import TYPE_CHECKING

from barcode.base import Barcode
from barcode.charsets import codabar
from barcode.errors import BarcodeError
from barcode.errors import IllegalCharacterError

if TYPE_CHECKING:
from barcode.writer import BaseWriter


class CODABAR(Barcode):
"""Initializes a new CODABAR instance.
Expand All @@ -25,7 +30,13 @@ class CODABAR(Barcode):

name = "Codabar (NW-7)"

def __init__(self, code, writer=None, narrow=2, wide=5) -> None:
def __init__(
self,
code: str,
writer: BaseWriter | None = None,
narrow: int = 2,
wide: int = 5,
) -> None:
self.code = code
self.writer = writer or self.default_writer()
self.narrow = narrow
Expand All @@ -34,7 +45,7 @@ def __init__(self, code, writer=None, narrow=2, wide=5) -> None:
def __str__(self) -> str:
return self.code

def get_fullcode(self):
def get_fullcode(self) -> str:
return self.code

def build(self) -> list[str]:
Expand Down
37 changes: 26 additions & 11 deletions barcode/codex.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
if TYPE_CHECKING:
from collections.abc import Collection

from PIL.Image import Image as T_Image

from barcode.writer import BaseWriter

__docformat__ = "restructuredtext en"
Expand Down Expand Up @@ -45,7 +47,12 @@ class Code39(Barcode):

name = "Code 39"

def __init__(self, code: str, writer=None, add_checksum: bool = True) -> None:
def __init__(
self,
code: str,
writer: BaseWriter | None = None,
add_checksum: bool = True,
) -> None:
r"""
:param code: Code 39 string without \* and without checksum.
:param writer: A ``barcode.writer`` instance used to render the barcode
Expand Down Expand Up @@ -83,7 +90,11 @@ def build(self) -> list[str]:
result = code39.MIDDLE.join(chars)
return [result]

def render(self, writer_options=None, text=None):
def render(
self,
writer_options: dict | None = None,
text: str | None = None,
) -> bytes | T_Image:
options = {"module_width": MIN_SIZE, "quiet_zone": MIN_QUIET_ZONE}
options.update(writer_options or {})
return super().render(options, text)
Expand All @@ -100,7 +111,7 @@ class PZN7(Code39):

digits = 6

def __init__(self, pzn, writer=None) -> None:
def __init__(self, pzn: str, writer: BaseWriter | None = None) -> None:
pzn = pzn[: self.digits]
if not pzn.isdigit():
raise IllegalCharacterError("PZN can only contain numbers.")
Expand All @@ -112,10 +123,10 @@ def __init__(self, pzn, writer=None) -> None:
self.pzn = f"{pzn}{self.calculate_checksum()}"
super().__init__(f"PZN-{self.pzn}", writer, add_checksum=False)

def get_fullcode(self):
def get_fullcode(self) -> str:
return f"PZN-{self.pzn}"

def calculate_checksum(self):
def calculate_checksum(self) -> int:
sum_ = sum(int(x) * int(y) for x, y in enumerate(self.pzn, start=2))
checksum = sum_ % 11
if checksum == 10:
Expand Down Expand Up @@ -144,7 +155,7 @@ class Code128(Barcode):
writer: BaseWriter
buffer: str

def __init__(self, code: str, writer=None) -> None:
def __init__(self, code: str, writer: BaseWriter | None = None) -> None:
self.code = code
self.writer = writer or self.default_writer()
self._charset = "C"
Expand Down Expand Up @@ -174,7 +185,7 @@ def _new_charset(self, which: Literal["A", "B", "C"]) -> list[int]:
return [code]

# to be redefined in subclass if required
def _is_char_fnc1_char(self, char):
def _is_char_fnc1_char(self, char: str) -> bool:
"""Whether a character is the FNC1 character.

May be redefined by subclasses if required. FNC1 char is defined in GS1-128
Expand Down Expand Up @@ -307,7 +318,11 @@ def build(self) -> list[str]:
code += "11"
return [code]

def render(self, writer_options=None, text=None):
def render(
self,
writer_options: dict | None = None,
text: str | None = None,
) -> bytes | T_Image:
options = {"module_width": MIN_SIZE, "quiet_zone": MIN_QUIET_ZONE}
options.update(writer_options or {})
return super().render(options, text)
Expand All @@ -325,14 +340,14 @@ class Gs1_128(Code128): # noqa: N801

FNC1_CHAR = "\xf1"

def __init__(self, code, writer=None) -> None:
def __init__(self, code: str, writer: BaseWriter | None = None) -> None:
code = self.FNC1_CHAR + code
super().__init__(code, writer)

def get_fullcode(self):
def get_fullcode(self) -> str:
return super().get_fullcode()[1:]

def _is_char_fnc1_char(self, char):
def _is_char_fnc1_char(self, char: str) -> bool:
return char == self.FNC1_CHAR


Expand Down
28 changes: 22 additions & 6 deletions barcode/ean.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,19 @@

__docformat__ = "restructuredtext en"

from typing import TYPE_CHECKING

from barcode.base import Barcode
from barcode.charsets import ean as _ean
from barcode.errors import IllegalCharacterError
from barcode.errors import NumberOfDigitsError
from barcode.errors import WrongCountryCodeError

if TYPE_CHECKING:
from PIL.Image import Image as T_Image

from barcode.writer import BaseWriter

# EAN13 Specs (all sizes in mm)
SIZES = {
"SC0": 0.27,
Expand Down Expand Up @@ -44,7 +50,7 @@ class EuropeanArticleNumber13(Barcode):
def __init__(
self,
ean: str,
writer=None,
writer: BaseWriter | None = None,
no_checksum: bool = False,
guardbar: bool = False,
) -> None:
Expand Down Expand Up @@ -125,7 +131,11 @@ def to_ascii(self) -> str:
code = code_list[0]
return code.replace("G", "|").replace("1", "|").replace("0", " ")

def render(self, writer_options: dict | None = None, text: str | None = None):
def render(
self,
writer_options: dict | None = None,
text: str | None = None,
) -> bytes | T_Image:
options = {"module_width": SIZES["SC2"]}
options.update(writer_options or {})
return super().render(options, text)
Expand All @@ -136,7 +146,13 @@ class EuropeanArticleNumber13WithGuard(EuropeanArticleNumber13):

name = "EAN-13 with guards"

def __init__(self, ean, writer=None, no_checksum=False, guardbar=True) -> None:
def __init__(
self,
ean: str,
writer: BaseWriter | None = None,
no_checksum: bool = False,
guardbar: bool = True,
) -> None:
super().__init__(ean, writer, no_checksum, guardbar)


Expand All @@ -151,7 +167,7 @@ class JapanArticleNumber(EuropeanArticleNumber13):

valid_country_codes = list(range(450, 460)) + list(range(490, 500))

def __init__(self, jan, *args, **kwargs) -> None:
def __init__(self, jan: str, *args, **kwargs) -> None:
if int(jan[:3]) not in self.valid_country_codes:
raise WrongCountryCodeError(
"Country code isn't between 450-460 or 490-500."
Expand Down Expand Up @@ -184,7 +200,7 @@ def build(self) -> list[str]:
code += self.EDGE
return [code]

def get_fullcode(self):
def get_fullcode(self) -> str:
if self.guardbar:
return "< " + self.ean[:4] + " " + self.ean[4:] + " >"
return self.ean
Expand All @@ -198,7 +214,7 @@ class EuropeanArticleNumber8WithGuard(EuropeanArticleNumber8):
def __init__(
self,
ean: str,
writer=None,
writer: BaseWriter | None = None,
no_checksum: bool = False,
guardbar: bool = True,
) -> None:
Expand Down
2 changes: 1 addition & 1 deletion barcode/errors.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


class BarcodeError(Exception):
def __init__(self, msg) -> None:
def __init__(self, msg: str) -> None:
self.msg = msg

def __str__(self) -> str:
Expand Down
23 changes: 17 additions & 6 deletions barcode/isxn.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,15 @@

from __future__ import annotations

from typing import TYPE_CHECKING

from barcode.ean import EuropeanArticleNumber13
from barcode.errors import BarcodeError
from barcode.errors import WrongCountryCodeError

if TYPE_CHECKING:
from barcode.writer import BaseWriter

__docformat__ = "restructuredtext en"


Expand All @@ -40,7 +45,13 @@ class InternationalStandardBookNumber13(EuropeanArticleNumber13):

name = "ISBN-13"

def __init__(self, isbn, writer=None, no_checksum=False, guardbar=False) -> None:
def __init__(
self,
isbn: str,
writer: BaseWriter | None = None,
no_checksum: bool = False,
guardbar: bool = False,
) -> None:
isbn = isbn.replace("-", "")
self.isbn13 = isbn
if isbn[:3] not in ("978", "979"):
Expand All @@ -62,14 +73,14 @@ class InternationalStandardBookNumber10(InternationalStandardBookNumber13):

isbn_digits = 9

def __init__(self, isbn, writer=None) -> None:
def __init__(self, isbn: str, writer: BaseWriter | None = None) -> None:
isbn = isbn.replace("-", "")
isbn = isbn[: self.isbn_digits]
super().__init__("978" + isbn, writer)
self.isbn10 = isbn
self.isbn10 = f"{isbn}{self._calculate_checksum()}"

def _calculate_checksum(self):
def _calculate_checksum(self) -> int | str:
tmp = sum(x * int(y) for x, y in enumerate(self.isbn10[:9], start=1)) % 11
if tmp == 10:
return "X"
Expand All @@ -92,14 +103,14 @@ class InternationalStandardSerialNumber(EuropeanArticleNumber13):

issn_digits = 7

def __init__(self, issn, writer=None) -> None:
def __init__(self, issn: str, writer: BaseWriter | None = None) -> None:
issn = issn.replace("-", "")
issn = issn[: self.issn_digits]
self.issn = issn
self.issn = f"{issn}{self._calculate_checksum()}"
super().__init__(self.make_ean(), writer)

def _calculate_checksum(self):
def _calculate_checksum(self) -> int | str:
tmp = (
11
- sum(x * int(y) for x, y in enumerate(reversed(self.issn[:7]), start=2))
Expand All @@ -110,7 +121,7 @@ def _calculate_checksum(self):

return tmp

def make_ean(self):
def make_ean(self) -> str:
return f"977{self.issn[:7]}00{self._calculate_checksum()}"

def __str__(self) -> str:
Expand Down
Loading
Loading