diff --git a/docs/conf.py b/docs/conf.py index d4a34b7b..fa3698b3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -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 @@ -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 @@ -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 @@ -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'), ] diff --git a/sandbox/benchmarks.py b/sandbox/benchmarks.py index 62ed1e27..43dede54 100644 --- a/sandbox/benchmarks.py +++ b/sandbox/benchmarks.py @@ -2,7 +2,6 @@ """\ Some benchmarks running against QR Code generators """ -from __future__ import print_function import sys import os import csv @@ -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): @@ -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) diff --git a/sandbox/make_charts.py b/sandbox/make_charts.py index b238a1d0..9299bcb6 100644 --- a/sandbox/make_charts.py +++ b/sandbox/make_charts.py @@ -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__': diff --git a/segno/__init__.py b/segno/__init__.py index f33f3625..47dbe21c 100644 --- a/segno/__init__.py +++ b/segno/__init__.py @@ -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 @@ -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): @@ -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): """\ @@ -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}'") diff --git a/segno/__init__.pyi b/segno/__init__.pyi index 838f3a33..808a15a0 100644 --- a/segno/__init__.pyi +++ b/segno/__init__.pyi @@ -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: ... @@ -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, @@ -82,13 +84,13 @@ 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: ... @@ -96,10 +98,10 @@ class QRCode: 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: ... diff --git a/segno/cli.py b/segno/cli.py index 7b6d5694..934a19d0 100644 --- a/segno/cli.py +++ b/segno/cli.py @@ -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%%, ' @@ -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 @@ -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 diff --git a/segno/encoder.py b/segno/encoder.py index 02d3aa0e..845a3695 100644 --- a/segno/encoder.py +++ b/segno/encoder.py @@ -21,7 +21,7 @@ from collections import namedtuple from . import consts from itertools import zip_longest -import sys # noqa: E402 +import sys _MAX_PENALTY_SCORE = sys.maxsize del sys @@ -61,18 +61,15 @@ def encode(content, error=None, version=None, mode=None, mask=None, """ version = normalize_version(version) if not micro and micro is not None and version in consts.MICRO_VERSIONS: - raise ValueError('A Micro QR Code version ("{0}") is provided but ' - 'parameter "micro" is False' - .format(get_version_name(version))) + raise ValueError(f'A Micro QR Code version ("{get_version_name(version)}") ' + 'is provided but parameter "micro" is False') if micro and version is not None and version not in consts.MICRO_VERSIONS: - raise ValueError('Illegal Micro QR Code version "{0}"' - .format(get_version_name(version))) + raise ValueError(f'Illegal Micro QR Code version "{get_version_name(version)}"') error = normalize_errorlevel(error, accept_none=True) mode = normalize_mode(mode) if mode is not None and version is not None \ and not is_mode_supported(mode, version): - raise ValueError('Mode "{0}" is not available in version "{1}"' - .format(get_mode_name(mode), get_version_name(version))) + raise ValueError(f'Mode "{get_mode_name(mode)}" is not available in version "{get_version_name(version)}"') if error == consts.ERROR_LEVEL_H and (micro or version in consts.MICRO_VERSIONS): raise ValueError('Error correction level "H" is not available for Micro QR Codes') if eci and (micro or version in consts.MICRO_VERSIONS): @@ -82,8 +79,8 @@ def encode(content, error=None, version=None, mode=None, mask=None, if version is None: version = guessed_version elif guessed_version > version: - raise DataOverflowError('The provided data does not fit into version "{0}". Proposal: version {1}' - .format(get_version_name(version), get_version_name(guessed_version))) + raise DataOverflowError(f'The provided data does not fit into version "{get_version_name(version)}"' + f'Proposal: version {get_version_name(guessed_version)}') if error is None and version != consts.VERSION_M1: error = consts.ERROR_LEVEL_L is_micro = version < 1 @@ -91,9 +88,8 @@ def encode(content, error=None, version=None, mode=None, mask=None, return _encode(segments, error, version, mask, eci, boost_error) -def encode_sequence(content, error=None, version=None, mode=None, - mask=None, encoding=None, eci=False, boost_error=True, - symbol_count=None): +def encode_sequence(content, error=None, version=None, mode=None, mask=None, + encoding=None, eci=False, boost_error=True, symbol_count=None): """\ EXPERIMENTAL: Creates a sequence of QR codes in Structured Append mode. @@ -155,7 +151,7 @@ def number_of_symbols_by_version(content, version, error, mode): if version is not None: if version < 1: raise ValueError('This function does not accept Micro QR Code versions. ' - 'Provided: "{0}"'.format(get_version_name(version))) + f'Provided: "{get_version_name(version)}"') elif symbol_count is None: raise ValueError('Please provide either a QR Code version or the symbol count') if symbol_count is not None and not 1 <= symbol_count <= 16: @@ -186,13 +182,13 @@ def number_of_symbols_by_version(content, version, error, mode): if mode == consts.MODE_NUMERIC: content = str(content) if symbol_count is not None and len(content) < symbol_count: - raise ValueError('The content is not long enough to be divided into {0} symbols'.format(symbol_count)) + raise ValueError(f'The content is not long enough to be divided into {symbol_count} symbols') sa_parity_data = calc_structured_append_parity(content) num_symbols = symbol_count or 16 if version is not None: num_symbols = number_of_symbols_by_version(content, version, error, mode) if num_symbols > 16: - raise DataOverflowError('The data does not fit into Structured Append version {0}'.format(version)) + raise DataOverflowError(f'The data does not fit into Structured Append version {version}') chunks = divide_into_chunks(content, num_symbols) if symbol_count is not None: segments = one_item_segments(max(chunks, key=len), mode) @@ -508,7 +504,7 @@ def add_codewords(matrix, codewords, version): idx += 1 if idx != len(codewords): # pragma: no cover raise ValueError('Internal error: Adding codewords to matrix failed. ' - 'Added {0} of {1} codewords'.format(idx, len(codewords))) + f'Added {idx} of {len(codewords)} codewords') def make_final_message(version, error, buff): @@ -717,7 +713,7 @@ def mask_scores(matrix, width, height): :param matrix: The matrix to evaluate :param matrix_size: The width (or height) of the matrix. :return tuple: A tuple of penalty scores (ints): ``(n1, n2, n3, n4)``. - """ + """ # noqa: RUF002 n3_pattern = bytearray((0x1, 0x0, 0x1, 0x1, 0x1, 0x0, 0x1)) def n3_pattern_occurrences(seq): @@ -1031,10 +1027,9 @@ def make_segment(data, mode, encoding=None): if segment_mode is not None: # Check if user provided mode is applicable for the given segment_data if segment_mode < guessed_mode: - raise ValueError('The provided mode "{0}" is not applicable for {1}. Proposal: {2}' - .format(get_mode_name(segment_mode), - repr(segment_data), - get_mode_name(guessed_mode))) + raise ValueError(f'The provided mode "{get_mode_name(segment_mode)}" ' + f'is not applicable for {segment_data!r}. ' + f'Proposal: {get_mode_name(guessed_mode)}') else: segment_mode = guessed_mode if segment_mode != consts.MODE_BYTE: @@ -1086,7 +1081,7 @@ def make_segment(data, mode, encoding=None): # a) Subtract A6A1HEX from GB2312 value; diff = code - 0xa6a1 else: # pragma: no cover - raise ValueError('Invalid Hanzi bytes: {0}'.format(code)) + raise ValueError(f'Invalid Hanzi bytes: {code}') # b) Multiply most significant byte of result by 60HEX; # c) Add least significant byte to product from b); # d) Convert result to a 13-bit binary string. @@ -1104,7 +1099,7 @@ def make_segment(data, mode, encoding=None): # Subtract C140HEX from Shift JIS value; diff = code - 0xc140 else: # pragma: no cover - raise ValueError('Invalid Kanji bytes: {0}'.format(code)) + raise ValueError(f'Invalid Kanji bytes: {code}') # b) Multiply most significant byte of result by C0HEX; # c) Add least significant byte to product from b); # d) Convert result to a 13-bit binary string. @@ -1185,8 +1180,8 @@ def normalize_version(version): except (KeyError, AttributeError): error = True if error or not 0 < version < 41 and version not in consts.MICRO_VERSIONS: - raise ValueError('Unsupported version "{0}". Supported: {1} and 1 .. 40' - .format(version, ', '.join(sorted(consts.MICRO_VERSION_MAPPING.keys())))) + raise ValueError(f'Unsupported version "{version}". ' + f'Supported: {", ".join(sorted(consts.MICRO_VERSION_MAPPING.keys()))} and 1 .. 40') return version @@ -1209,8 +1204,8 @@ def normalize_mode(mode): try: return consts.MODE_MAPPING[mode.lower()] except (KeyError, AttributeError): - raise ValueError('Illegal mode "{0}". Supported values: {1}' - .format(mode, ', '.join(sorted(consts.MODE_MAPPING.keys())))) + raise ValueError(f'Illegal mode "{mode}". ' + f'Supported values: {", ".join(sorted(consts.MODE_MAPPING.keys()))}') def normalize_mask(mask, is_micro): @@ -1229,14 +1224,14 @@ def normalize_mask(mask, is_micro): try: mask = int(mask) except ValueError: - raise ValueError('Invalid data mask "{0}". ' - 'Must be an integer or a string which represents an integer value.'.format(mask)) + raise ValueError(f'Invalid data mask "{mask}". ' + 'Must be an integer or a string which represents an integer value.') if is_micro: if not 0 <= mask < 4: - raise ValueError('Invalid data mask "{0}" for Micro QR Code. Must be in range 0 .. 3'.format(mask)) + raise ValueError(f'Invalid data mask "{mask}" for Micro QR Code. Must be in range 0 .. 3') else: if not 0 <= mask < 8: - raise ValueError('Invalid data mask "{0}". Must be in range 0 .. 7'.format(mask)) + raise ValueError(f'Invalid data mask "{mask}". Must be in range 0 .. 7') return mask @@ -1263,8 +1258,7 @@ def normalize_errorlevel(error, accept_none=False): except (KeyError, AttributeError): if error in consts.ERROR_MAPPING.values(): return error - raise ValueError('Illegal error correction level: "{0}". Supported levels: L, M, Q, H' - .format(error)) + raise ValueError(f'Illegal error correction level: "{error}". Supported levels: L, M, Q, H') def get_mode_name(mode_const): @@ -1278,7 +1272,7 @@ def get_mode_name(mode_const): for name, val in consts.MODE_MAPPING.items(): if val == mode_const: return name - raise ValueError('Unknown mode "{0}"'.format(mode_const)) + raise ValueError(f'Unknown mode "{mode_const}"') def get_error_name(error_const): @@ -1292,7 +1286,7 @@ def get_error_name(error_const): for name, val in consts.ERROR_MAPPING.items(): if val == error_const: return name - raise ValueError('Unknown error level "{0}"'.format(error_const)) + raise ValueError('Unknown error level "{error_const}"') def get_version_name(version_const): @@ -1310,7 +1304,7 @@ def get_version_name(version_const): for name, v in consts.MICRO_VERSION_MAPPING.items(): if v == version_const: return name - raise ValueError('Unknown version constant "{0}"'.format(version_const)) + raise ValueError(f'Unknown version constant "{version_const}"') _ALPHANUMERIC_PATTERN = re.compile(br'^[' + re.escape(consts.ALPHANUMERIC_CHARS) + br']+\Z') @@ -1396,7 +1390,7 @@ def find_version(segments, error, eci, micro, is_sa=False): help_txt = '(Micro) ' elif micro: help_txt = 'Micro ' - raise DataOverflowError('Data too large. No {0}QR Code can handle the provided data'.format(help_txt)) + raise DataOverflowError(f'Data too large. No {help_txt}QR Code can handle the provided data') def calc_matrix_size(ver): @@ -1448,7 +1442,7 @@ def is_mode_supported(mode, ver): try: return ver in consts.SUPPORTED_MODES[mode] except KeyError: - raise ValueError('Unknown mode "{0}"'.format(mode)) + raise ValueError(f'Unknown mode "{mode}"') def find_minimum_version_for_mode(mode): @@ -1480,7 +1474,7 @@ def version_range(version): return consts.VERSION_RANGE_10_26 elif 26 < version < 41: return consts.VERSION_RANGE_27_40 - raise ValueError('Unknown version "{0}"'.format(version)) + raise ValueError(f'Unknown version "{version}"') def get_eci_assignment_number(encoding): @@ -1493,8 +1487,7 @@ def get_eci_assignment_number(encoding): try: return consts.ECI_ASSIGNMENT_NUM[codecs.lookup(encoding).name] except KeyError: - raise ValueError('Unknown ECI assignment number for encoding "{0}".' - .format(encoding)) + raise ValueError(f'Unknown ECI assignment number for encoding "{encoding}".') def get_data_mask_functions(is_micro): @@ -1690,7 +1683,7 @@ def __new__(cls, number, total, parity): :param int total: Total symbol count ``[2 .. 15]`` :param int parity: Parity data. """ - return super(_StructuredAppendInfo, cls).__new__(cls, (consts.MODE_STRUCTURED_APPEND, number, total, parity)) + return super().__new__(cls, (consts.MODE_STRUCTURED_APPEND, number, total, parity)) mode = property(itemgetter(0)) number = property(itemgetter(1)) diff --git a/segno/helpers.pyi b/segno/helpers.pyi index e680be65..1bf6893d 100644 --- a/segno/helpers.pyi +++ b/segno/helpers.pyi @@ -1,105 +1,105 @@ from . import QRCode import decimal import datetime -from typing import Optional, Union, Iterable +from typing import Iterable -def make_wifi_data(ssid: str, password: Optional[str], security: Optional[str], +def make_wifi_data(ssid: str, password: str | None, security: str | None, hidden: bool = False) -> str: ... -def make_wifi(ssid: str, password: Optional[str], security: Optional[str], +def make_wifi(ssid: str, password: str | None, security: str | None, hidden: bool = False) -> QRCode: ... -def make_mecard_data(name: Union[str, Iterable[str]], - reading: Optional[str] = None, - email: Optional[Union[str, Iterable[str]]] = None, - phone: Optional[Union[str, Iterable[str]]] = None, - videophone: Optional[Union[str, Iterable[str]]] = None, - memo: Optional[str] = None, - nickname: Optional[str] = None, - birthday: Optional[Union[str, datetime.date]] = None, - url: Optional[Union[str, Iterable[str]]] = None, - pobox: Optional[str] = None, - roomno: Optional[str] = None, - houseno: Optional[str] = None, - city: Optional[str] = None, - prefecture: Optional[str] = None, - zipcode: Optional[str] = None, - country: Optional[str] = None) -> str: ... - - -def make_mecard(name: Union[str, Iterable[str]], - reading: Optional[str] = None, - email: Optional[Union[str, Iterable[str]]] = None, - phone: Optional[Union[str, Iterable[str]]] = None, - videophone: Optional[Union[str, Iterable[str]]] = None, - memo: Optional[str] = None, - nickname: Optional[str] = None, - birthday: Optional[Union[str, datetime.date]] = None, - url: Optional[Union[str, Iterable[str]]] = None, - pobox: Optional[str] = None, - roomno: Optional[str] = None, - houseno: Optional[str] = None, - city: Optional[str] = None, - prefecture: Optional[str] = None, - zipcode: Optional[str] = None, - country: Optional[str] = None) -> QRCode: ... +def make_mecard_data(name: str | Iterable[str], + reading: str | None = None, + email: str | Iterable[str] | None = None, + phone: str | Iterable[str] | None = None, + videophone: str | Iterable[str] | None = None, + memo: str | None = None, + nickname: str | None = None, + birthday: str | datetime.date | None = None, + url: str | Iterable[str] | None = None, + pobox: str | None = None, + roomno: str | None = None, + houseno: str | None = None, + city: str | None = None, + prefecture: str | None = None, + zipcode: str | None = None, + country: str | None = None) -> str: ... + + +def make_mecard(name: str | Iterable[str], + reading: str | None = None, + email: str | Iterable[str] | None = None, + phone: str | Iterable[str] | None = None, + videophone: str | Iterable[str] | None = None, + memo: str | None = None, + nickname: str | None = None, + birthday: str | datetime.date | None = None, + url: str | Iterable[str] | None = None, + pobox: str | None = None, + roomno: str | None = None, + houseno: str | None = None, + city: str | None = None, + prefecture: str | None = None, + zipcode: str | None = None, + country: str | None = None) -> QRCode: ... def make_vcard_data(name: str, displayname: str, - email: Optional[Union[str, Iterable[str]]] = None, - phone: Optional[Union[str, Iterable[str]]] = None, - fax: Optional[Union[str, Iterable[str]]] = None, - videophone: Optional[Union[str, Iterable[str]]] = None, - memo: Optional[str] = None, - nickname: Optional[str] = None, - birthday: Optional[Union[str, datetime.date]] = None, - url: Optional[Union[str, Iterable[str]]] = None, - pobox: Optional[str] = None, - street: Optional[str] = None, - city: Optional[str] = None, - region: Optional[str] = None, - zipcode: Optional[str] = None, - country: Optional[str] = None, - org: Optional[str] = None, - lat: Optional[float] = None, - lng: Optional[float] = None, - source: Optional[str] = None, - rev: Optional[Union[str, datetime.date]] = None, - title: Optional[Union[str, Iterable[str]]] = None, - photo_uri: Optional[Union[str, Iterable[str]]] = None, - cellphone: Optional[Union[str, Iterable[str]]] = None, - homephone: Optional[Union[str, Iterable[str]]] = None, - workphone: Optional[Union[str, Iterable[str]]] = None) -> str: ... + email: str | Iterable[str] | None = None, + phone: str | Iterable[str] | None = None, + fax: str | Iterable[str] | None = None, + videophone: str | Iterable[str] | None = None, + memo: str | None = None, + nickname: str | None = None, + birthday: str | datetime.date | None = None, + url: str | Iterable[str] | None = None, + pobox: str | None = None, + street: str | None = None, + city: str | None = None, + region: str | None = None, + zipcode: str | None = None, + country: str | None = None, + org: str | None = None, + lat: float | None = None, + lng: float | None = None, + source: str | None = None, + rev: str | datetime.date | None = None, + title: str | Iterable[str] | None = None, + photo_uri: str | Iterable[str] | None = None, + cellphone: str | Iterable[str] | None = None, + homephone: str | Iterable[str] | None = None, + workphone: str | Iterable[str] | None = None) -> str: ... def make_vcard(name: str, displayname: str, - email: Optional[Union[str, Iterable[str]]] = None, - phone: Optional[Union[str, Iterable[str]]] = None, - fax: Optional[Union[str, Iterable[str]]] = None, - videophone: Optional[Union[str, Iterable[str]]] = None, - memo: Optional[str] = None, - nickname: Optional[str] = None, - birthday: Optional[Union[str, datetime.date]] = None, - url: Optional[Union[str, Iterable[str]]] = None, - pobox: Optional[str] = None, - street: Optional[str] = None, - city: Optional[str] = None, - region: Optional[str] = None, - zipcode: Optional[str] = None, - country: Optional[str] = None, - org: Optional[str] = None, - lat: Optional[float] = None, - lng: Optional[float] = None, - source: Optional[str] = None, - rev: Optional[Union[str, datetime.date]] = None, - title: Optional[Union[str, Iterable[str]]] = None, - photo_uri: Optional[Union[str, Iterable[str]]] = None, - cellphone: Optional[Union[str, Iterable[str]]] = None, - homephone: Optional[Union[str, Iterable[str]]] = None, - workphone: Optional[Union[str, Iterable[str]]] = None) -> QRCode: ... + email: str | Iterable[str] | None = None, + phone: str | Iterable[str] | None = None, + fax: str | Iterable[str] | None = None, + videophone: str | Iterable[str] | None = None, + memo: str | None = None, + nickname: str | None = None, + birthday: str | datetime.date | None = None, + url: str | Iterable[str] | None = None, + pobox: str | None = None, + street: str | None = None, + city: str | None = None, + region: str | None = None, + zipcode: str | None = None, + country: str | None = None, + org: str | None = None, + lat: float | None = None, + lng: float | None = None, + source: str | None = None, + rev: str | datetime.date | None = None, + title: str | Iterable[str] | None = None, + photo_uri: str | Iterable[str] | None = None, + cellphone: str | Iterable[str] | None = None, + homephone: str | Iterable[str] | None = None, + workphone: str | Iterable[str] | None = None) -> QRCode: ... def make_geo_data(lat: float, lng: float) -> str: ... @@ -108,23 +108,23 @@ def make_geo_data(lat: float, lng: float) -> str: ... def make_geo(lat: float, lng: float) -> QRCode: ... -def make_make_email_data(to: Union[str, Iterable[str]], - cc: Optional[Union[str, Iterable[str]]] = None, - bcc: Optional[Union[str, Iterable[str]]] = None, - subject: Optional[str] = None, - body: Optional[str] = None) -> str: ... +def make_make_email_data(to: str | Iterable[str], + cc: str | Iterable[str] | None = None, + bcc: str | Iterable[str] | None = None, + subject: str | None = None, + body: str | None = None) -> str: ... -def make_email(to: Union[str, Iterable[str]], - cc: Optional[Union[str, Iterable[str]]] = None, - bcc: Optional[Union[str, Iterable[str]]] = None, - subject: Optional[str] = None, - body: Optional[str] = None) -> QRCode: ... +def make_email(to: str | Iterable[str], + cc: str | Iterable[str] | None = None, + bcc: str | Iterable[str] | None = None, + subject: str | None = None, + body: str | None = None) -> QRCode: ... -def make_epc_qr(name: str, iban: str, amount: Union[int, float, decimal.Decimal], - text: Optional[str] = None, - reference: Optional[str] = None, - bic: Optional[str] = None, - purpose: Optional[str] = None, - encoding: Optional[Union[str, int]] = None) -> QRCode: ... +def make_epc_qr(name: str, iban: str, amount: int | float | decimal.Decimal, + text: str | None = None, + reference: str | None = None, + bic: str | None = None, + purpose: str | None = None, + encoding: str | int | None = None) -> QRCode: ... diff --git a/segno/utils.py b/segno/utils.py index 5a8c5ef9..ee4170c9 100644 --- a/segno/utils.py +++ b/segno/utils.py @@ -76,7 +76,7 @@ def check_valid_scale(scale): :type scale: float or int """ if scale <= 0: - raise ValueError('The scale must not be negative or zero. Got: "{0}"'.format(scale)) + raise ValueError(f'The scale must not be negative or zero. Got: "{scale}"') def check_valid_border(border): @@ -86,7 +86,7 @@ def check_valid_border(border): :param int border: Indicating the size of the quiet zone. """ if border is not None and (int(border) != border or border < 0): - raise ValueError('The border must not a non-negative integer value. Got: "{0}"'.format(border)) + raise ValueError(f'The border must not a non-negative integer value. Got: "{border}"') def matrix_to_lines(matrix, x, y, incby=1):