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 Stephan Sokolow
Thijs Triemstra Thijs Triemstra
Thomas van den Berg Thomas van den Berg
tuxmaster
vendryan vendryan
Yaisel Hurtado Yaisel Hurtado
ysuolmai ysuolmai

View File

@ -47,14 +47,14 @@ def print_codepage(printer, codepage):
# Table header # Table header
printer.set(font="b") 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() printer.set()
# The table # The table
for x in range(0, 16): for x in range(0, 16):
# First column # First column
printer.set(font="b") printer.set(font="b")
printer._raw("{} ".format(hex(x)[2:])) printer._raw(f"{hex(x)[2:]} ")
printer.set() printer.set()
for y in range(0, 16): for y in range(0, 16):

View File

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

View File

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

View File

@ -72,7 +72,7 @@ class BarcodeTypeError(Error):
def __str__(self): def __str__(self):
"""Return string representation of BarcodeTypeError.""" """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): class BarcodeSizeError(Error):
@ -97,7 +97,7 @@ class BarcodeSizeError(Error):
def __str__(self): def __str__(self):
"""Return string representation of BarcodeSizeError.""" """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): class BarcodeCodeError(Error):
@ -122,7 +122,7 @@ class BarcodeCodeError(Error):
def __str__(self): def __str__(self):
"""Return string representation of BarcodeCodeError.""" """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): class ImageSizeError(Error):
@ -145,9 +145,7 @@ class ImageSizeError(Error):
def __str__(self): def __str__(self):
"""Return string representation of ImageSizeError.""" """Return string representation of ImageSizeError."""
return "Image height is longer than 255px and can't be printed ({msg})".format( return f"Image height is longer than 255px and can't be printed ({self.msg})"
msg=self.msg
)
class ImageWidthError(Error): class ImageWidthError(Error):
@ -170,7 +168,7 @@ class ImageWidthError(Error):
def __str__(self): def __str__(self):
"""Return string representation of ImageWidthError.""" """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): class TextError(Error):
@ -194,9 +192,7 @@ class TextError(Error):
def __str__(self): def __str__(self):
"""Return string representation of TextError.""" """Return string representation of TextError."""
return "Text string must be supplied to the text() method ({msg})".format( return f"Text string must be supplied to the text() method ({self.msg})"
msg=self.msg
)
class CashDrawerError(Error): class CashDrawerError(Error):
@ -220,7 +216,7 @@ class CashDrawerError(Error):
def __str__(self): def __str__(self):
"""Return string representation of CashDrawerError.""" """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): class TabPosError(Error):
@ -247,9 +243,7 @@ class TabPosError(Error):
def __str__(self): def __str__(self):
"""Return string representation of TabPosError.""" """Return string representation of TabPosError."""
return "Valid tab positions must be in the range 0 to 16 ({msg})".format( return f"Valid tab positions must be in the range 0 to 16 ({self.msg})"
msg=self.msg
)
class CharCodeError(Error): class CharCodeError(Error):
@ -273,7 +267,7 @@ class CharCodeError(Error):
def __str__(self): def __str__(self):
"""Return string representation of CharCodeError.""" """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): class DeviceNotFoundError(Error):
@ -345,7 +339,7 @@ class SetVariableError(Error):
def __str__(self): def __str__(self):
"""Return string representation of SetVariableError.""" """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 # Configuration errors
@ -372,7 +366,7 @@ class ConfigNotFoundError(Error):
def __str__(self): def __str__(self):
"""Return string representation of ConfigNotFoundError.""" """Return string representation of ConfigNotFoundError."""
return "Configuration not found ({msg})".format(msg=self.msg) return f"Configuration not found ({self.msg})"
class ConfigSyntaxError(Error): class ConfigSyntaxError(Error):
@ -396,7 +390,7 @@ class ConfigSyntaxError(Error):
def __str__(self): def __str__(self):
"""Return string representation of ConfigSyntaxError.""" """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): class ConfigSectionMissingError(Error):
@ -420,4 +414,4 @@ class ConfigSectionMissingError(Error):
def __str__(self): def __str__(self):
"""Return string representation of ConfigSectionMissingError.""" """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: if encoding not in self.codepages:
raise ValueError( raise ValueError(
( (
'Encoding "{}" cannot be used for the current profile. ' f'Encoding "{encoding}" cannot be used for the current profile. '
"Valid encodings are: {}" f'Valid encodings are: {",".join(self.codepages.keys())}'
).format(encoding, ",".join(self.codepages.keys())) )
) )
return encoding return encoding
@ -88,7 +88,7 @@ class Encoder(object):
# Non-encodable character, just skip it # Non-encodable character, just skip it
pass pass
return encodable_chars 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): def _get_codepage_char_map(self, encoding):
"""Get codepage character map. """Get codepage character map.
@ -294,9 +294,7 @@ class MagicEncode(object):
"""Write the text and inject necessary codepage switches.""" """Write the text and inject necessary codepage switches."""
if text is not None and type(text) is not six.text_type: if text is not None and type(text) is not six.text_type:
raise Error( raise Error(
"The supplied text has to be unicode, but is of type {type}.".format( f"The supplied text has to be unicode, but is of type {type(text)}."
type=type(text)
)
) )
# We always know the current code page; if the new codepage # We always know the current code page; if the new codepage