Skip to content

Commit

Permalink
Modernized code: f-strings, improved typing information
Browse files Browse the repository at this point in the history
  • Loading branch information
heuer committed Feb 23, 2024
1 parent 505e558 commit df4f20c
Show file tree
Hide file tree
Showing 9 changed files with 231 additions and 238 deletions.
8 changes: 3 additions & 5 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
#
# All configuration values have a default; values that are commented out
# serve to show the default.
from __future__ import unicode_literals
import os
import sys
import sphinx_rtd_theme
Expand Down Expand Up @@ -55,7 +54,7 @@

# General information about the project.
project = 'Segno'
copyright = '2016 - 2024 Lars Heuer -- "QR Code" and "Micro QR Code" are registered trademarks of DENSO WAVE INCORPORATED.'
copyright = '2016 - 2024 Lars Heuer -- "QR Code" and "Micro QR Code" are registered trademarks of DENSO WAVE INCORPORATED.' # noqa: E501
author = 'Lars Heuer'

# The version info for the project you're documenting, acts as replacement for
Expand Down Expand Up @@ -240,8 +239,7 @@
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'segno.tex', u'Segno Documentation',
u'Author', 'manual'),
(master_doc, 'segno.tex', 'Segno Documentation', 'Author', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
Expand Down Expand Up @@ -283,7 +281,7 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'segno', u'Segno Documentation',
(master_doc, 'segno', 'Segno Documentation',
author, 'segno', 'One line description of project.',
'Miscellaneous'),
]
Expand Down
47 changes: 23 additions & 24 deletions sandbox/benchmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
"""\
Some benchmarks running against QR Code generators
"""
from __future__ import print_function
import sys
import os
import csv
Expand Down Expand Up @@ -131,31 +130,31 @@ def run_create_tests(which=None, number=200, table=None):
_run_tests(tests, number, table)


def run_create7q_tests(which=None, number=200, table=None):
tests = ('create7q_qrcodegen',
'create7q_qrcode',
'create7q_segno',)
if which:
tests = filter(lambda n: n[len('create7q_'):] in which, tests)
_run_tests(tests, number, table)
# def run_create7q_tests(which=None, number=200, table=None):
# tests = ('create7q_qrcodegen',
# 'create7q_qrcode',
# 'create7q_segno',)
# if which:
# tests = filter(lambda n: n[len('create7q_'):] in which, tests)
# _run_tests(tests, number, table)


def run_create30h_tests(which=None, number=200, table=None):
tests = ('create30h_qrcodegen',
'create30h_qrcode',
'create30h_segno',)
if which:
tests = filter(lambda n: n[len('createbig_'):] in which, tests)
_run_tests(tests, number, table)
# def run_create30h_tests(which=None, number=200, table=None):
# tests = ('create30h_qrcodegen',
# 'create30h_qrcode',
# 'create30h_segno',)
# if which:
# tests = filter(lambda n: n[len('createbig_'):] in which, tests)
# _run_tests(tests, number, table)


def run_svg_tests(which=None, number=200, table=None):
tests = ('svg_qrcode_path', 'svg_qrcode_rects',
'svg_segno',)
# def run_svg_tests(which=None, number=200, table=None):
# tests = ('svg_qrcode_path', 'svg_qrcode_rects',
# 'svg_segno',)

if which:
tests = filter(lambda n: n[len('svg_'):] in which, tests)
_run_tests(tests, number, table)
# if which:
# tests = filter(lambda n: n[len('svg_'):] in which, tests)
# _run_tests(tests, number, table)


def run_png_tests(which=None, number=200, table=None):
Expand Down Expand Up @@ -186,9 +185,9 @@ def _run_tests(tests, number, table=None):
if __name__ == '__main__':
table = []
run_create_tests(table=table)
run_create7q_tests(table=table)
run_create30h_tests(table=table)
run_svg_tests(table=table)
#run_create7q_tests(table=table)
#run_create30h_tests(table=table)
#run_svg_tests(table=table)
run_png_tests(table=table)
with open(os.path.join(_output_dir(), 'results.csv'), 'w') as f:
writer = csv.writer(f)
Expand Down
19 changes: 12 additions & 7 deletions sandbox/make_charts.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,19 @@ def create_charts():
elif ' SVG' in name:
svg_data.append((name.replace(' SVG', ''), val))
output_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../docs/_static/')
for data, title, filename in ((create_1m_data, 'Create a 1-M QR Code', os.path.join(output_dir, 'chart_create_1m.svg')),
(create_7q_data, 'Create a 7-Q QR Code', os.path.join(output_dir, 'chart_create_7q.svg')),
(create_30h_data, 'Create a 30-H QR Code', os.path.join(output_dir, 'chart_create_30h.svg')),
(svg_data, 'Create a 1-M QR Code and write SVG', os.path.join(output_dir, 'chart_svg.svg')),
(png_data, 'Create a 1-M QR Code and write PNG', os.path.join(output_dir, 'chart_png.svg'))):
for data, title, filename in ((create_1m_data, 'Create a 1-M QR Code',
os.path.join(output_dir, 'chart_create_1m.svg')),
(create_7q_data, 'Create a 7-Q QR Code',
os.path.join(output_dir, 'chart_create_7q.svg')),
(create_30h_data, 'Create a 30-H QR Code',
os.path.join(output_dir, 'chart_create_30h.svg')),
(svg_data, 'Create a 1-M QR Code and write SVG',
os.path.join(output_dir, 'chart_svg.svg')),
(png_data, 'Create a 1-M QR Code and write PNG',
os.path.join(output_dir, 'chart_png.svg'))):
create_chart(title,
[(name, [{'value': float(val), 'color': color_map[name], 'label': name}]) for name, val in sorted(data, key=lambda t: Decimal(t[1]))],
filename)
[(name, [{'value': float(val), 'color': color_map[name], 'label': name}])
for name, val in sorted(data, key=lambda t: Decimal(t[1]))], filename)


if __name__ == '__main__':
Expand Down
10 changes: 4 additions & 6 deletions segno/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ def delete_file(name):
f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False)
try:
self.save(f, scale=scale, dark=dark, light=light, border=border)
except: # noqa: E722
except:
f.close()
os.unlink(f.name)
raise
Expand Down Expand Up @@ -961,8 +961,7 @@ def __getattr__(self, name):
name=name[3:]):
plugin = ep.load()
return partial(plugin, self)
raise AttributeError('{0} object has no attribute {1}'
.format(self.__class__, name))
raise AttributeError(f'{self.__class__} object has no attribute {name}')


class QRCodeSequence(tuple):
Expand All @@ -974,7 +973,7 @@ class QRCodeSequence(tuple):
__slots__ = ()

def __new__(cls, qrcodes):
return super(QRCodeSequence, cls).__new__(cls, qrcodes)
return super().__new__(cls, qrcodes)

def terminal(self, out=None, border=None, compact=False):
"""\
Expand Down Expand Up @@ -1016,5 +1015,4 @@ def __getattr__(self, item):
"""
if len(self) == 1:
return getattr(self[0], item)
raise AttributeError("{0} object has no attribute '{1}'"
.format(self.__class__, item))
raise AttributeError(f"{self.__class__} object has no attribute '{item}'")
92 changes: 47 additions & 45 deletions segno/__init__.pyi
Original file line number Diff line number Diff line change
@@ -1,58 +1,60 @@
from typing import Any, AnyStr, Callable, Optional, Tuple, Union, IO, TextIO, Iterator, Iterable
from typing import Any, AnyStr, Callable, IO, TextIO, Iterator, Iterable
from .encoder import DataOverflowError as DataOverflowError

__version__ : str

def make(content: Union[int, str, bytes],
error: Optional[str] = None,
version: Optional[Union[int, str]] = None,
mode: Optional[str] = None,
mask: Optional[int] = None,
encoding: Optional[str] = None,

def make(content: int | str | bytes,
error: str | None = None,
version: int | str | None = None,
mode: str | None = None,
mask: int | None = None,
encoding: str | None = None,
eci: bool = False,
micro: Optional[bool] = None,
micro: bool | None = None,
boost_error: bool = True) -> QRCode: ...


def make_qr(content: Union[int, str, bytes],
error: Optional[str] = None,
version: Optional[Union[int, str]] = None,
mode: Optional[str] = None,
mask: Optional[int] = None,
encoding: Optional[str] = None,
def make_qr(content: int | str | bytes,
error: str | None = None,
version: int | str | None = None,
mode: str | None = None,
mask: int | None = None,
encoding: str | None = None,
eci: bool = False, boost_error: bool = True) -> QRCode: ...


def make_micro(content: Union[int, str, bytes],
error: Optional[str] = None,
version: Optional[Union[int, str]] = None,
mode: Optional[str] = None,
mask: Optional[int] = None,
encoding: Optional[str] = None,
def make_micro(content: int | str | bytes,
error: str | None = None,
version: int | str | None = None,
mode: str | None = None,
mask: int | None = None,
encoding: str | None = None,
boost_error: bool = True) -> QRCode: ...


def make_sequence(content: Union[int, str, bytes],
error: Optional[str] = None,
version: Optional[Union[int, str]] = None,
mode: Optional[str] = None,
mask: Optional[int] = None,
encoding: Optional[str] = None,
def make_sequence(content: int | str | bytes,
error: str | None = None,
version: int | str | None = None,
mode: str | None = None,
mask: int | None = None,
encoding: str | None = None,
boost_error: bool = True,
symbol_count: Optional[int] = None) -> QRCodeSequence: ...
symbol_count: int | None = None) -> QRCodeSequence: ...


class QRCode:
matrix: Tuple[bytearray, ...]
matrix: tuple[bytearray, ...]
mask: int

@property
def version(self) -> Union[int, str]: ...
def version(self) -> int | str: ...

@property
def error(self) -> str: ...

@property
def mode(self) -> Optional[str]: ...
def mode(self) -> str | None: ...

@property
def designator(self) -> str: ...
Expand All @@ -63,16 +65,16 @@ class QRCode:
@property
def is_micro(self) -> bool: ...

def symbol_size(self, scale: Union[int, float] = 1,
border: Optional[int] = None) -> Tuple[Union[int, float], Union[int, float]]: ...
def symbol_size(self, scale: int | float = 1,
border: int | None = None) -> tuple[int | float, int | float]: ...

def matrix_iter(self, scale: Union[int, float] = 1,
border: Optional[int] = None,
def matrix_iter(self, scale: int | float = 1,
border: int | None = None,
verbose: bool = False) -> Iterator[Iterable[int]]: ...

def show(self, delete_after: Union[int, float] = 20, scale: Union[int, float] = 10,
border: Optional[int] = None, dark: Union[tuple, str] = '#000',
light: Union[tuple, str] = '#fff') -> None: ...
def show(self, delete_after: int | float = 20, scale: int | float = 10,
border: int | None = None, dark: tuple | str = '#000',
light: tuple | str = '#fff') -> None: ...

def svg_data_uri(self, xmldecl: bool = False, encode_minimal: bool = False,
omit_charset: bool = False, nl: bool = False,
Expand All @@ -82,24 +84,24 @@ class QRCode:

def png_data_uri(self, **kw: Any) -> str: ...

def terminal(self, out: Optional[Union[TextIO, str]] = None,
border: Optional[int] = None, compact: bool = False) -> None: ...
def terminal(self, out: TextIO | str | None = None,
border: int | None = None, compact: bool = False) -> None: ...

def save(self, out: Union[IO[AnyStr], str], kind: Optional[str] = None,
def save(self, out: IO[AnyStr] | str, kind: str | None = None,
**kw: Any) -> None: ...

def __getattr__(self, name: Any) -> Optional[Callable]: ...
def __getattr__(self, name: Any) -> Callable | None: ...

def __eq__(self, other: Any) -> bool: ...

__hash__: Any = None


class QRCodeSequence(tuple):
def terminal(self, out: Optional[Union[TextIO, str]] = None,
border: Optional[int] = None, compact: bool = False) -> None: ...
def terminal(self, out: TextIO | str | None = None,
border: int | None = None, compact: bool = False) -> None: ...

def save(self, out: Union[IO[AnyStr], str], kind: Optional[str] = None,
def save(self, out: IO[AnyStr] | str, kind: str | None = None,
**kw: Any) -> None: ...

def __getattr__(self, name: Any) -> Optional[Callable]: ...
def __getattr__(self, name: Any) -> Callable | None: ...
8 changes: 3 additions & 5 deletions segno/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ def _convert_scale(val):
return val if val != int(val) else int(val)

parser = argparse.ArgumentParser(prog='segno',
description='Segno QR Code and Micro QR Code generator version {0}'
.format(segno.__version__))
description=f'Segno QR Code and Micro QR Code generator version {segno.__version__}') # noqa: E501
parser.add_argument('--version', '-v', help='(Micro) QR Code version: 1 .. 40 or "M1", "M2", "M3", "M4"',
required=False,)
parser.add_argument('--error', '-e', help='Error correction level: "L": 7%% (default), "M": 15%%, "Q": 25%%, '
Expand Down Expand Up @@ -177,8 +176,7 @@ def _convert_scale(val):
action='store_true')
# Show Segno's version --version and -v are taken by QR Code version
parser.add_mutually_exclusive_group().add_argument('--ver', '-V', help="Shows Segno's version",
action='version',
version='Segno {0}'.format(segno.__version__))
action='version', version=f'Segno {segno.__version__}')
parser.add_argument('content', nargs='+', help='The content to encode')
return parser

Expand Down Expand Up @@ -294,7 +292,7 @@ class _AttrDict(dict):
Internal helper class.
"""
def __init__(self, *args, **kwargs):
super(_AttrDict, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.__dict__ = self


Expand Down
Loading

0 comments on commit df4f20c

Please sign in to comment.