Skip to content

Commit

Permalink
Use f-strings where sensible
Browse files Browse the repository at this point in the history
  • Loading branch information
akx committed Dec 25, 2023
1 parent b7cc900 commit 8ddad89
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 71 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ extend-select = [
"F63",
"F7",
"F82",
"FLY", # flynt
"I",
"S", # Bandit
"UP",
Expand Down
30 changes: 16 additions & 14 deletions src/paho/mqtt/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ def wait_for_publish(self, timeout=None):
elif self.rc == MQTT_ERR_AGAIN:
pass
elif self.rc > 0:
raise RuntimeError('Message publish failed: %s' % (error_string(self.rc)))
raise RuntimeError(f'Message publish failed: {error_string(self.rc)}')

timeout_time = None if timeout is None else time_func() + timeout
timeout_tenth = None if timeout is None else timeout / 10.
Expand All @@ -357,7 +357,7 @@ def is_published(self):
elif self.rc == MQTT_ERR_AGAIN:
pass
elif self.rc > 0:
raise RuntimeError('Message publish failed: %s' % (error_string(self.rc)))
raise RuntimeError(f'Message publish failed: {error_string(self.rc)}')

with self._condition:
return self._published
Expand Down Expand Up @@ -515,7 +515,7 @@ def __init__(self, client_id="", clean_session=None, userdata=None,

if transport.lower() not in ('websockets', 'tcp'):
raise ValueError(
'transport must be "websockets" or "tcp", not %s' % transport)
f'transport must be "websockets" or "tcp", not {transport}')
self._manual_ack = manual_ack
self._transport = transport.lower()
self._protocol = protocol
Expand Down Expand Up @@ -923,17 +923,17 @@ def connect_srv(self, domain=None, keepalive=60, bind_address="",
domain = domain[domain.find('.') + 1:]

try:
rr = '_mqtt._tcp.%s' % domain
rr = f'_mqtt._tcp.{domain}'
if self._ssl:
# IANA specifies secure-mqtt (not mqtts) for port 8883
rr = '_secure-mqtt._tcp.%s' % domain
rr = f'_secure-mqtt._tcp.{domain}'
answers = []
for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
addr = answer.target.to_text()[:-1]
answers.append(
(addr, answer.port, answer.priority, answer.weight))
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers) as err:
raise ValueError("No answer/NXDOMAIN for SRV in %s" % domain) from err
raise ValueError(f"No answer/NXDOMAIN for SRV in {domain}") from err

# FIXME: doesn't account for weight
for answer in answers:
Expand Down Expand Up @@ -2808,8 +2808,10 @@ def _send_connect(self, keepalive):
proto_ver |= 0x80

self._pack_remaining_length(packet, remaining_length)
packet.extend(struct.pack("!H" + str(len(protocol)) + "sBBH", len(protocol), protocol, proto_ver, connect_flags,
keepalive))
packet.extend(struct.pack(
f"!H{len(protocol)}sBBH",
len(protocol), protocol, proto_ver, connect_flags, keepalive,
))

if self._protocol == MQTTv5:
packet += packed_connect_properties
Expand Down Expand Up @@ -3273,7 +3275,7 @@ def _handle_disconnect(self):

def _handle_suback(self):
self._easy_log(MQTT_LOG_DEBUG, "Received SUBACK")
pack_format = "!H" + str(len(self._in_packet['packet']) - 2) + 's'
pack_format = f"!H{len(self._in_packet['packet']) - 2}s"
(mid, packet) = struct.unpack(pack_format, self._in_packet['packet'])

if self._protocol == MQTTv5:
Expand All @@ -3283,7 +3285,7 @@ def _handle_suback(self):
for c in packet[props_len:]:
reasoncodes.append(ReasonCodes(SUBACK >> 4, identifier=c))
else:
pack_format = "!" + "B" * len(packet)
pack_format = f"!{'B' * len(packet)}"
granted_qos = struct.unpack(pack_format, packet)

with self._callback_mutex:
Expand Down Expand Up @@ -3315,9 +3317,9 @@ def _handle_publish(self):
message.qos = (header & 0x06) >> 1
message.retain = (header & 0x01)

pack_format = "!H" + str(len(self._in_packet['packet']) - 2) + 's'
pack_format = f"!H{len(self._in_packet['packet']) - 2}s"
(slen, packet) = struct.unpack(pack_format, self._in_packet['packet'])
pack_format = '!' + str(slen) + 's' + str(len(packet) - slen) + 's'
pack_format = f"!{slen}s{len(packet) - slen}s"
(topic, packet) = struct.unpack(pack_format, packet)

if self._protocol != MQTTv5 and len(topic) == 0:
Expand All @@ -3330,12 +3332,12 @@ def _handle_publish(self):
try:
print_topic = topic.decode('utf-8')
except UnicodeDecodeError:
print_topic = "TOPIC WITH INVALID UTF-8: " + str(topic)
print_topic = f"TOPIC WITH INVALID UTF-8: {topic!r}"

message.topic = topic

if message.qos > 0:
pack_format = "!H" + str(len(packet) - 2) + 's'
pack_format = f"!H{len(packet) - 2}s"
(message.mid, packet) = struct.unpack(pack_format, packet)

if self._protocol == MQTTv5:
Expand Down
18 changes: 7 additions & 11 deletions src/paho/mqtt/properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ def __setattr__(self, name, value):
# the name could have spaces in, or not. Remove spaces before assignment
if name not in [aname.replace(' ', '') for aname in self.names.keys()]:
raise MQTTException(
"Property name must be one of "+str(self.names.keys()))
f"Property name must be one of {self.names.keys()}")
# check that this attribute applies to the packet type
if self.packetType not in self.properties[self.getIdentFromName(name)][1]:
raise MQTTException(f"Property {name} does not apply to packet type {PacketTypes.Names[self.packetType]}")
Expand All @@ -269,23 +269,20 @@ def __setattr__(self, name, value):
if name in ["ReceiveMaximum", "TopicAlias"] \
and (value < 1 or value > 65535):

raise MQTTException(
"%s property value must be in the range 1-65535" % (name))
raise MQTTException(f"{name} property value must be in the range 1-65535")
elif name in ["TopicAliasMaximum"] \
and (value < 0 or value > 65535):

raise MQTTException(
"%s property value must be in the range 0-65535" % (name))
raise MQTTException(f"{name} property value must be in the range 0-65535")
elif name in ["MaximumPacketSize", "SubscriptionIdentifier"] \
and (value < 1 or value > 268435455):

raise MQTTException(
"%s property value must be in the range 1-268435455" % (name))
raise MQTTException(f"{name} property value must be in the range 1-268435455")
elif name in ["RequestResponseInformation", "RequestProblemInformation", "PayloadFormatIndicator"] \
and (value != 0 and value != 1):

raise MQTTException(
"%s property value must be 0 or 1" % (name))
f"{name} property value must be 0 or 1")

if self.allowsMultiple(name):
if not isinstance(value, list):
Expand All @@ -302,8 +299,7 @@ def __str__(self):
if hasattr(self, compressedName):
if not first:
buffer += ", "
buffer += compressedName + " : " + \
str(getattr(self, compressedName))
buffer += f"{compressedName} : {getattr(self, compressedName)}"
first = False
buffer += "]"
return buffer
Expand Down Expand Up @@ -422,6 +418,6 @@ def unpack(self, buffer):
compressedName = propname.replace(' ', '')
if not self.allowsMultiple(compressedName) and hasattr(self, compressedName):
raise MQTTException(
"Property '%s' must not exist more than once" % property)
f"Property '{property}' must not exist more than once")
setattr(self, propname, value)
return self, propslen + VBIlen
2 changes: 1 addition & 1 deletion src/paho/mqtt/subscribeoptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def __init__(self, qos=0, noLocal=False, retainAsPublished=False, retainHandling
def __setattr__(self, name, value):
if name not in self.names:
raise MQTTException(
name + " Attribute name must be one of "+str(self.names))
f"{name} Attribute name must be one of {self.names}")
object.__setattr__(self, name, value)

def pack(self):
Expand Down
6 changes: 3 additions & 3 deletions tests/mqtt5_props.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,18 @@ def gen_uint32_prop(identifier, word):

def gen_string_prop(identifier, s):
s = s.encode("utf-8")
prop = struct.pack('!BH%ds'%(len(s)), identifier, len(s), s)
prop = struct.pack(f'!BH{len(s)}s', identifier, len(s), s)
return prop

def gen_string_pair_prop(identifier, s1, s2):
s1 = s1.encode("utf-8")
s2 = s2.encode("utf-8")
prop = struct.pack('!BH%dsH%ds'%(len(s1), len(s2)), identifier, len(s1), s1, len(s2), s2)
prop = struct.pack(f'!BH{len(s1)}sH{len(s2)}s', identifier, len(s1), s1, len(s2), s2)
return prop

def gen_varint_prop(identifier, val):
v = pack_varint(val)
return struct.pack("!B"+str(len(v))+"s", identifier, v)
return struct.pack(f"!B{len(v)}s", identifier, v)

def pack_varint(varint):
s = b""
Expand Down
15 changes: 7 additions & 8 deletions tests/paho_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,13 @@ def expect_packet(sock, name, expected):

def packet_matches(name, recvd, expected):
if recvd != expected:
print("FAIL: Received incorrect " + name + ".")
print(f"FAIL: Received incorrect {name}.")
try:
print("Received: " + to_string(recvd))
print(f"Received: {to_string(recvd)}")
except struct.error:
print("Received (not decoded): 0x" +
binascii.b2a_hex(recvd).decode('utf8'))
print(f"Received (not decoded): 0x{binascii.b2a_hex(recvd).decode('utf8')}")
try:
print("Expected: " + to_string(expected))
print(f"Expected: {to_string(expected)}")
except struct.error:
print("Expected (not decoded): 0x" +
binascii.b2a_hex(expected).decode('utf8'))
Expand Down Expand Up @@ -163,7 +162,7 @@ def do_client_connect(connect_packet, connack_packet, hostname="localhost", port

def remaining_length(packet):
l = min(5, len(packet)) # noqa: E741
all_bytes = struct.unpack("!" + "B" * l, packet[:l])
all_bytes = struct.unpack(f"!{'B' * l}", packet[:l])
mult = 1
rl = 0
for i in range(1, l - 1):
Expand Down Expand Up @@ -195,7 +194,7 @@ def to_string(packet):
if len(packet) == 0:
return ""

packet0 = struct.unpack("!B%ds" % (len(packet)-1), bytes(packet))
packet0 = struct.unpack(f"!B{len(packet) - 1}s", bytes(packet))
packet0 = packet0[0]
cmd = packet0 & 0xF0
if cmd == 0x00:
Expand Down Expand Up @@ -388,7 +387,7 @@ def mqtt_read_string(sock, rl):
slen = sock.recv(2)
slen, = struct.unpack("!H", slen)
payload = sock.recv(slen)
payload, = struct.unpack("!%ds" % (slen), payload)
payload, = struct.unpack(f"!{slen}s", payload)
rl -= (2 + slen)
return (payload, rl)

Expand Down
Loading

0 comments on commit 8ddad89

Please sign in to comment.