Refactor to using f-strings (#608)

* update authors

* refactor to using f-strings
This commit is contained in:
Patrick Kanzler 2023-12-11 00:34:29 +01:00 committed by GitHub
parent dcc71ce47d
commit 91cbc264fc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 37 additions and 60 deletions

View File

@ -46,6 +46,7 @@ Sergio Pulgarin
Stephan Sokolow
Thijs Triemstra
Thomas van den Berg
tuxmaster
vendryan
Yaisel Hurtado
ysuolmai

View File

@ -47,14 +47,14 @@ def print_codepage(printer, codepage):
# Table header
printer.set(font="b")
printer._raw(" {}\n".format(sep.join(map(lambda s: hex(s)[2:], range(0, 16)))))
printer._raw(f" {sep.join(map(lambda s: hex(s)[2:], range(0, 16)))}\n")
printer.set()
# The table
for x in range(0, 16):
# First column
printer.set(font="b")
printer._raw("{} ".format(hex(x)[2:]))
printer._raw(f"{hex(x)[2:]} ")
printer.set()
for y in range(0, 16):

View File

@ -18,9 +18,7 @@ logging.basicConfig()
logger = logging.getLogger(__name__)
pickle_dir = environ.get("ESCPOS_CAPABILITIES_PICKLE_DIR", mkdtemp())
pickle_path = path.join(
pickle_dir, "{v}.capabilities.pickle".format(v=platform.python_version())
)
pickle_path = path.join(pickle_dir, f"{platform.python_version()}.capabilities.pickle")
# get a temporary file from importlib_resources if no file is specified in env
file_manager = ExitStack()
atexit.register(file_manager.close)
@ -114,9 +112,7 @@ class BaseProfile(object):
"""
font = {"a": 0, "b": 1}.get(font, font)
if not six.text_type(font) in self.fonts:
raise NotSupported(
'"{}" is not a valid font in the current profile'.format(font)
)
raise NotSupported(f'"{font}" is not a valid font in the current profile')
return font
def get_columns(self, font):
@ -158,7 +154,7 @@ def get_profile_class(name: str) -> Type[BaseProfile]:
profiles: Dict[str, Any] = CAPABILITIES["profiles"]
profile_data = profiles[name]
profile_name = clean(name)
class_name = "{}{}Profile".format(profile_name[0].upper(), profile_name[1:])
class_name = f"{profile_name[0].upper()}{profile_name[1:]}Profile"
new_class = type(class_name, (BaseProfile,), {"profile_data": profile_data})
CLASS_CACHE[name] = new_class

View File

@ -80,9 +80,7 @@ class Config(object):
if not self._printer_name or not hasattr(printer, self._printer_name):
raise exceptions.ConfigSyntaxError(
'Printer type "{printer_name}" is invalid'.format(
printer_name=self._printer_name,
)
f'Printer type "{self._printer_name}" is invalid'
)
self._has_loaded = True

View File

@ -219,7 +219,7 @@ class Escpos(object):
max_width = int(self.profile.profile_data["media"]["width"]["pixels"])
if im.width > max_width:
raise ImageWidthError("{} > {}".format(im.width, max_width))
raise ImageWidthError(f"{im.width} > {max_width}")
if center:
im.center(max_width)
@ -420,9 +420,7 @@ class Escpos(object):
raise ValueError("Can only output 1-4 bytes")
if not 0 <= inp_number <= max_input:
raise ValueError(
"Number too large. Can only output up to {0} in {1} bytes".format(
max_input, out_bytes
)
f"Number too large. Can only output up to {max_input} in {out_bytes} bytes"
)
outp = b""
for _ in range(0, out_bytes):
@ -711,21 +709,15 @@ class Escpos(object):
if not function_type or not BARCODE_TYPES.get(function_type.upper()):
raise BarcodeTypeError(
(
"Barcode '{bc}' not valid for barcode function type "
"{function_type}"
).format(
bc=bc,
function_type=function_type,
f"Barcode '{bc}' not valid for barcode function type "
f"{function_type}"
)
)
bc_types = BARCODE_TYPES[function_type.upper()]
if check and not self.check_barcode(bc, code):
raise BarcodeCodeError(
("Barcode '{code}' not in a valid format for type '{bc}'").format(
code=code,
bc=bc,
)
f"Barcode '{code}' not in a valid format for type '{bc}'"
)
# Align Bar Code()
@ -735,12 +727,12 @@ class Escpos(object):
if 1 <= height <= 255:
self._raw(BARCODE_HEIGHT + six.int2byte(height))
else:
raise BarcodeSizeError("height = {height}".format(height=height))
raise BarcodeSizeError(f"height = {height}")
# Width
if 2 <= width <= 6:
self._raw(BARCODE_WIDTH + six.int2byte(width))
else:
raise BarcodeSizeError("width = {width}".format(width=width))
raise BarcodeSizeError(f"width = {width}")
# Font
if font.upper() == "B":
self._raw(BARCODE_FONT_B)
@ -833,9 +825,7 @@ class Escpos(object):
# Check if barcode type exists
if barcode_type not in barcode.PROVIDED_BARCODES:
raise BarcodeTypeError(
"Barcode type {} not supported by software barcode renderer".format(
barcode_type
)
f"Barcode type {barcode_type} not supported by software barcode renderer"
)
# Render the barcode
@ -878,7 +868,7 @@ class Escpos(object):
:param txt: text to be printed with a newline
:raises: :py:exc:`~escpos.exceptions.TextError`
"""
self.text("{}\n".format(txt))
self.text(f"{txt}\n")
def ln(self, count=1):
"""Print a newline or more.
@ -1426,7 +1416,7 @@ class EscposIO(object):
lines = text
else:
lines = [
"{0}".format(text),
f"{text}",
]
# TODO check unicode handling
@ -1434,9 +1424,9 @@ class EscposIO(object):
for line in lines:
self.printer.set(**params)
if isinstance(text, six.text_type):
self.printer.text("{0}\n".format(line))
self.printer.text(f"{line}\n")
else:
self.printer.text("{0}\n".format(line))
self.printer.text(f"{line}\n")
def close(self):
"""Close printer.

View File

@ -72,7 +72,7 @@ class BarcodeTypeError(Error):
def __str__(self):
"""Return string representation of BarcodeTypeError."""
return "No Barcode type is defined ({msg})".format(msg=self.msg)
return f"No Barcode type is defined ({self.msg})"
class BarcodeSizeError(Error):
@ -97,7 +97,7 @@ class BarcodeSizeError(Error):
def __str__(self):
"""Return string representation of BarcodeSizeError."""
return "Barcode size is out of range ({msg})".format(msg=self.msg)
return f"Barcode size is out of range ({self.msg})"
class BarcodeCodeError(Error):
@ -122,7 +122,7 @@ class BarcodeCodeError(Error):
def __str__(self):
"""Return string representation of BarcodeCodeError."""
return "No Barcode code was supplied ({msg})".format(msg=self.msg)
return f"No Barcode code was supplied ({self.msg})"
class ImageSizeError(Error):
@ -145,9 +145,7 @@ class ImageSizeError(Error):
def __str__(self):
"""Return string representation of ImageSizeError."""
return "Image height is longer than 255px and can't be printed ({msg})".format(
msg=self.msg
)
return f"Image height is longer than 255px and can't be printed ({self.msg})"
class ImageWidthError(Error):
@ -170,7 +168,7 @@ class ImageWidthError(Error):
def __str__(self):
"""Return string representation of ImageWidthError."""
return "Image width is too large ({msg})".format(msg=self.msg)
return f"Image width is too large ({self.msg})"
class TextError(Error):
@ -194,9 +192,7 @@ class TextError(Error):
def __str__(self):
"""Return string representation of TextError."""
return "Text string must be supplied to the text() method ({msg})".format(
msg=self.msg
)
return f"Text string must be supplied to the text() method ({self.msg})"
class CashDrawerError(Error):
@ -220,7 +216,7 @@ class CashDrawerError(Error):
def __str__(self):
"""Return string representation of CashDrawerError."""
return "Valid pin must be set to send pulse ({msg})".format(msg=self.msg)
return f"Valid pin must be set to send pulse ({self.msg})"
class TabPosError(Error):
@ -247,9 +243,7 @@ class TabPosError(Error):
def __str__(self):
"""Return string representation of TabPosError."""
return "Valid tab positions must be in the range 0 to 16 ({msg})".format(
msg=self.msg
)
return f"Valid tab positions must be in the range 0 to 16 ({self.msg})"
class CharCodeError(Error):
@ -273,7 +267,7 @@ class CharCodeError(Error):
def __str__(self):
"""Return string representation of CharCodeError."""
return "Valid char code must be set ({msg})".format(msg=self.msg)
return f"Valid char code must be set ({self.msg})"
class DeviceNotFoundError(Error):
@ -345,7 +339,7 @@ class SetVariableError(Error):
def __str__(self):
"""Return string representation of SetVariableError."""
return "Set variable out of range ({msg})".format(msg=self.msg)
return f"Set variable out of range ({self.msg})"
# Configuration errors
@ -372,7 +366,7 @@ class ConfigNotFoundError(Error):
def __str__(self):
"""Return string representation of ConfigNotFoundError."""
return "Configuration not found ({msg})".format(msg=self.msg)
return f"Configuration not found ({self.msg})"
class ConfigSyntaxError(Error):
@ -396,7 +390,7 @@ class ConfigSyntaxError(Error):
def __str__(self):
"""Return string representation of ConfigSyntaxError."""
return "Configuration syntax is invalid ({msg})".format(msg=self.msg)
return f"Configuration syntax is invalid ({self.msg})"
class ConfigSectionMissingError(Error):
@ -420,4 +414,4 @@ class ConfigSectionMissingError(Error):
def __str__(self):
"""Return string representation of ConfigSectionMissingError."""
return "Configuration section is missing ({msg})".format(msg=self.msg)
return f"Configuration section is missing ({self.msg})"

View File

@ -57,9 +57,9 @@ class Encoder(object):
if encoding not in self.codepages:
raise ValueError(
(
'Encoding "{}" cannot be used for the current profile. '
"Valid encodings are: {}"
).format(encoding, ",".join(self.codepages.keys()))
f'Encoding "{encoding}" cannot be used for the current profile. '
f'Valid encodings are: {",".join(self.codepages.keys())}'
)
)
return encoding
@ -88,7 +88,7 @@ class Encoder(object):
# Non-encodable character, just skip it
pass
return encodable_chars
raise LookupError("Can't find a known encoding for {}".format(encoding))
raise LookupError(f"Can't find a known encoding for {encoding}")
def _get_codepage_char_map(self, encoding):
"""Get codepage character map.
@ -294,9 +294,7 @@ class MagicEncode(object):
"""Write the text and inject necessary codepage switches."""
if text is not None and type(text) is not six.text_type:
raise Error(
"The supplied text has to be unicode, but is of type {type}.".format(
type=type(text)
)
f"The supplied text has to be unicode, but is of type {type(text)}."
)
# We always know the current code page; if the new codepage