Skip to content

Commit 909f037

Browse files
committed
Add a lot more type hints
1 parent ec3ae09 commit 909f037

9 files changed

Lines changed: 61 additions & 45 deletions

File tree

barcode/__init__.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030
if TYPE_CHECKING:
3131
import os
3232

33+
from barcode.writer import BaseWriter
34+
3335
__BARCODE_MAP = {
3436
"ean8": EAN8,
3537
"ean8-guard": EAN8_GUARD,
@@ -62,7 +64,7 @@
6264
def get(
6365
name: str,
6466
code: str | None = None,
65-
writer=None,
67+
writer: BaseWriter | None = None,
6668
options: dict | None = None,
6769
):
6870
"""Helper method for getting a generator or even a generated code.
@@ -87,18 +89,18 @@ def get(
8789
return barcode
8890

8991

90-
def get_class(name):
92+
def get_class(name: str):
9193
return get_barcode(name)
9294

9395

9496
def generate(
9597
name: str,
9698
code: str,
97-
writer=None,
99+
writer: BaseWriter | None = None,
98100
output: str | (os.PathLike | (BinaryIO | None)) = None,
99101
writer_options: dict | None = None,
100102
text: str | None = None,
101-
):
103+
) -> str | None:
102104
"""Shortcut to generate a barcode in one line.
103105
104106
:param name: Name of the type of barcode to use.

barcode/base.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@
33
"""
44
from __future__ import annotations
55

6+
from typing import TYPE_CHECKING
67
from typing import ClassVar
78

89
from barcode.writer import BaseWriter
910
from barcode.writer import SVGWriter
1011

12+
if TYPE_CHECKING:
13+
from typing import BinaryIO
14+
1115

1216
class Barcode:
1317
name = ""
@@ -65,17 +69,18 @@ def save(
6569

6670
return self.writer.save(filename, output)
6771

68-
def write(self, fp, options=None, text=None):
72+
def write(
73+
self,
74+
fp: BinaryIO,
75+
options: dict | None = None,
76+
text: str | None = None,
77+
) -> None:
6978
"""Renders the barcode and writes it to the file like object
7079
`fp`.
7180
72-
:parameters:
73-
fp : File like object
74-
Object to write the raw data in.
75-
options : Dict
76-
The same as in `self.render`.
77-
text : str
78-
Text to render under the barcode.
81+
:param fp: Object to write the raw data in.
82+
:param options: The same as in `self.render`.
83+
:param text: Text to render under the barcode.
7984
"""
8085
output = self.render(options, text)
8186
self.writer.write(output, fp)

barcode/pybarcode.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@
55

66
import barcode
77
from barcode.version import version
8+
from barcode.writer import BaseWriter
89
from barcode.writer import ImageWriter
910
from barcode.writer import SVGWriter
1011

1112
IMG_FORMATS = ("BMP", "GIF", "JPEG", "MSP", "PCX", "PNG", "TIFF", "XBM")
1213

1314

14-
def list_types(args, parser=None):
15+
def list_types(args, parser=None) -> None:
1516
print("\npython-barcode available barcode formats:")
1617
print(", ".join(barcode.PROVIDED_BARCODES))
1718
print("\n")
@@ -24,7 +25,7 @@ def list_types(args, parser=None):
2425
print("\n")
2526

2627

27-
def create_barcode(args, parser):
28+
def create_barcode(args, parser) -> None:
2829
args.type = args.type.upper()
2930
if args.type != "SVG" and args.type not in IMG_FORMATS:
3031
parser.error(f"Unknown type {args.type}. Try list action for available types.")
@@ -34,8 +35,9 @@ def create_barcode(args, parser):
3435
f"Unknown barcode {args.barcode}. Try list action for available barcodes."
3536
)
3637
if args.type != "SVG":
38+
assert ImageWriter is not None
3739
opts = {"format": args.type}
38-
writer = ImageWriter()
40+
writer: BaseWriter = ImageWriter()
3941
else:
4042
opts = {"compress": args.compress}
4143
writer = SVGWriter()
@@ -44,7 +46,7 @@ def create_barcode(args, parser):
4446
print(f"New barcode saved as {name}.")
4547

4648

47-
def main():
49+
def main() -> None:
4850
msg = []
4951
if ImageWriter is None:
5052
msg.append("Image output disabled (Pillow not found), --type option disabled.")

barcode/writer.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,9 @@ def render(self, code):
308308

309309
return self._callbacks["finish"]()
310310

311+
def write(self, content, fp: BinaryIO) -> None:
312+
raise NotImplementedError
313+
311314

312315
class SVGWriter(BaseWriter):
313316
def __init__(self) -> None:
@@ -400,7 +403,7 @@ def save(self, filename, output):
400403
f.write(output)
401404
return _filename
402405

403-
def write(self, content, fp: BinaryIO):
406+
def write(self, content, fp: BinaryIO) -> None:
404407
"""Write `content` into a file-like object.
405408
406409
Content should be a barcode rendered by this writer.
@@ -409,7 +412,7 @@ def write(self, content, fp: BinaryIO):
409412

410413

411414
if Image is None:
412-
ImageWriter = None
415+
ImageWriter: type | None = None
413416
else:
414417

415418
class ImageWriter(BaseWriter): # type: ignore[no-redef]
@@ -463,15 +466,15 @@ def _paint_text(self, xpos, ypos):
463466
)
464467
ypos += pt2mm(self.font_size) / 2 + self.text_line_distance
465468

466-
def _finish(self):
469+
def _finish(self) -> Image:
467470
return self._image
468471

469-
def save(self, filename, output):
472+
def save(self, filename: str, output) -> str:
470473
filename = f"{filename}.{self.format.lower()}"
471474
output.save(filename, self.format.upper())
472475
return filename
473476

474-
def write(self, content, fp: BinaryIO):
477+
def write(self, content, fp: BinaryIO) -> None:
475478
"""Write `content` into a file-like object.
476479
477480
Content should be a barcode rendered by this writer.

tests/test_builds.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33
from barcode import get_barcode
44

55

6-
def test_ean8_builds():
6+
def test_ean8_builds() -> None:
77
ref = "1010100011000110100100110101111010101000100100010011100101001000101"
88
ean = get_barcode("ean8", "40267708")
99
bc = ean.build()
1010
assert ref == bc[0]
1111

1212

13-
def test_ean8_builds_with_longer_bars():
13+
def test_ean8_builds_with_longer_bars() -> None:
1414
ref = "G0G01000110001101001001101011110G0G01000100100010011100101001000G0G"
1515
ean = get_barcode("ean8", "40267708", options={"guardbar": True})
1616
bc = ean.build()

tests/test_checksums.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,46 +3,46 @@
33
from barcode import get_barcode
44

55

6-
def test_code39_checksum():
6+
def test_code39_checksum() -> None:
77
code39 = get_barcode("code39", "Code39")
88
assert code39.get_fullcode() == "CODE39W"
99

1010

11-
def test_pzn_checksum():
11+
def test_pzn_checksum() -> None:
1212
pzn = get_barcode("pzn", "103940")
1313
assert pzn.get_fullcode() == "PZN-1039406"
1414

1515

16-
def test_ean13_checksum():
16+
def test_ean13_checksum() -> None:
1717
ean = get_barcode("ean13", "400614457735")
1818
assert ean.get_fullcode() == "4006144577350"
1919

2020

21-
def test_ean8_checksum():
21+
def test_ean8_checksum() -> None:
2222
ean = get_barcode("ean8", "6032299")
2323
assert ean.get_fullcode() == "60322999"
2424

2525

26-
def test_jan_checksum():
26+
def test_jan_checksum() -> None:
2727
jan = get_barcode("jan", "491400614457")
2828
assert jan.get_fullcode() == "4914006144575"
2929

3030

31-
def test_ean14_checksum():
31+
def test_ean14_checksum() -> None:
3232
ean = get_barcode("ean14", "1234567891258")
3333
assert ean.get_fullcode() == "12345678912589"
3434

3535

36-
def test_isbn10_checksum():
36+
def test_isbn10_checksum() -> None:
3737
isbn = get_barcode("isbn10", "376926085")
3838
assert isbn.isbn10 == "3769260856"
3939

4040

41-
def test_isbn13_checksum():
41+
def test_isbn13_checksum() -> None:
4242
isbn = get_barcode("isbn13", "978376926085")
4343
assert isbn.get_fullcode() == "9783769260854"
4444

4545

46-
def test_gs1_128_checksum():
46+
def test_gs1_128_checksum() -> None:
4747
gs1_128 = get_barcode("gs1_128", "00376401856400470087")
4848
assert gs1_128.get_fullcode() == "00376401856400470087"

tests/test_init.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,17 @@
1212
TESTPATH = os.path.join(PATH, "test_outputs")
1313

1414

15-
def test_generate_without_output():
15+
def test_generate_without_output() -> None:
1616
with pytest.raises(TypeError, match="'output' cannot be None"):
1717
barcode.generate("ean13", "123455559121112")
1818

1919

20-
def test_generate_with_file():
20+
def test_generate_with_file() -> None:
2121
with open(os.path.join(TESTPATH, "generate_with_file.jpeg"), "wb") as f:
2222
barcode.generate("ean13", "123455559121112", output=f)
2323

2424

25-
def test_generate_with_filepath():
25+
def test_generate_with_filepath() -> None:
2626
# FIXME: extension is added to the filepath even if you include it.
2727
rv = barcode.generate(
2828
"ean13",
@@ -32,12 +32,12 @@ def test_generate_with_filepath():
3232
assert rv == os.path.abspath(os.path.join(TESTPATH, "generate_with_filepath.svg"))
3333

3434

35-
def test_generate_with_file_and_writer():
35+
def test_generate_with_file_and_writer() -> None:
3636
with open(os.path.join(TESTPATH, "generate_with_file_and_writer.jpeg"), "wb") as f:
3737
barcode.generate("ean13", "123455559121112", output=f, writer=SVGWriter())
3838

3939

40-
def test_generate_with_bytesio():
40+
def test_generate_with_bytesio() -> None:
4141
bio = BytesIO()
4242
barcode.generate("ean13", "123455559121112", output=bio)
4343
# XXX: File is not 100% deterministic; needs to be addressed at some point.

tests/test_manually.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,15 +50,15 @@
5050
)
5151

5252

53-
def test_generating_barcodes():
53+
def test_generating_barcodes() -> None:
5454
os.makedirs(TESTPATH, exist_ok=True)
5555

5656
objects = []
5757

58-
def append(x, y):
58+
def append(x, y) -> None:
5959
objects.append(OBJECTS.format(filename=x, name=y))
6060

61-
def append_img(x, y):
61+
def append_img(x, y) -> None:
6262
objects.append(IMAGES.format(filename=x, name=y))
6363

6464
options = {}

tests/test_writers.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,20 @@
1010
PATH = os.path.dirname(os.path.abspath(__file__))
1111
TESTPATH = os.path.join(PATH, "test_outputs")
1212

13-
if ImageWriter:
13+
if ImageWriter is not None:
14+
15+
def test_saving_image_to_byteio() -> None:
16+
assert ImageWriter is not None # workaround for mypy
1417

15-
def test_saving_image_to_byteio():
1618
rv = BytesIO()
1719
EAN13(str(100000902922), writer=ImageWriter()).write(rv)
1820

1921
with open(f"{TESTPATH}/somefile.jpeg", "wb") as f:
2022
EAN13("100000011111", writer=ImageWriter()).write(f)
2123

22-
def test_saving_rgba_image():
24+
def test_saving_rgba_image() -> None:
25+
assert ImageWriter is not None # workaround for mypy
26+
2327
rv = BytesIO()
2428
EAN13(str(100000902922), writer=ImageWriter()).write(rv)
2529

@@ -31,15 +35,15 @@ def test_saving_rgba_image():
3135
)
3236

3337

34-
def test_saving_svg_to_byteio():
38+
def test_saving_svg_to_byteio() -> None:
3539
rv = BytesIO()
3640
EAN13(str(100000902922), writer=SVGWriter()).write(rv)
3741

3842
with open(f"{TESTPATH}/somefile.svg", "wb") as f:
3943
EAN13("100000011111", writer=SVGWriter()).write(f)
4044

4145

42-
def test_saving_svg_to_byteio_with_guardbar():
46+
def test_saving_svg_to_byteio_with_guardbar() -> None:
4347
rv = BytesIO()
4448
EAN13(str(100000902922), writer=SVGWriter(), guardbar=True).write(rv)
4549

0 commit comments

Comments
 (0)