Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use f-strings for formatting #178

Merged
merged 3 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions examples/simple_2way.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@


def print_fader_handler(unused_addr, args, value):
print("[{0}] ~ {1:0.2f}".format(args[0], value))
print(f"[{args[0]}] ~ {value:0.2f}")


def print_xy_fader_handler(unused_addr, args, value1, value2):
print("[{0}] ~ {1:0.2f} ~ {2:0.2f}".format(args[0], value2, value1))
print(f"[{args[0]}] ~ {value2:0.2f} ~ {value1:0.2f}")


if __name__ == "__main__":
Expand Down Expand Up @@ -54,7 +54,7 @@ def print_xy_fader_handler(unused_addr, args, value1, value2):
def start_server(ip, port):
print("Starting Server")
server = osc_server.ThreadingOSCUDPServer((ip, port), dispatcher)
print("Serving on {}".format(server.server_address))
print(f"Serving on {server.server_address}")
thread = threading.Thread(target=server.serve_forever)
thread.start()

Expand Down
2 changes: 1 addition & 1 deletion examples/simple_echo_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ def echo_handler(client_addr, unused_addr, args):
dispatcher.set_default_handler(echo_handler, True)

server = osc_server.ThreadingOSCUDPServer((args.ip, args.port), dispatcher)
print("Serving on {}".format(server.server_address))
print(f"Serving on {server.server_address}")
server.serve_forever()
6 changes: 3 additions & 3 deletions examples/simple_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@


def print_volume_handler(unused_addr, args, volume):
print("[{0}] ~ {1}".format(args[0], volume))
print(f"[{args[0]}] ~ {volume}")


def print_compute_handler(unused_addr, args, volume):
try:
print("[{0}] ~ {1}".format(args[0], args[1](volume)))
print(f"[{args[0]}] ~ {args[1](volume)}")
except ValueError:
pass

Expand All @@ -34,5 +34,5 @@ def print_compute_handler(unused_addr, args, volume):
dispatcher.map("/logvolume", print_compute_handler, "Log volume", math.log)

server = osc_server.ThreadingOSCUDPServer((args.ip, args.port), dispatcher)
print("Serving on {}".format(server.server_address))
print(f"Serving on {server.server_address}")
server.serve_forever()
6 changes: 3 additions & 3 deletions examples/simple_tcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@


def print_volume_handler(unused_addr, args, volume):
print("[{0}] ~ {1}".format(args[0], volume))
print(f"[{args[0]}] ~ {volume}")


def print_compute_handler(unused_addr, args, volume):
try:
print("[{0}] ~ {1}".format(args[0], args[1](volume)))
print(f"[{args[0]}] ~ {args[1](volume)}")
except ValueError:
pass

Expand All @@ -42,5 +42,5 @@ def print_compute_handler(unused_addr, args, volume):
server = osc_tcp_server.ThreadingOSCTCPServer(
(args.ip, args.port), dispatcher, mode=args.mode
)
print("Serving on {}".format(server.server_address))
print(f"Serving on {server.server_address}")
server.serve_forever()
5 changes: 2 additions & 3 deletions pythonosc/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ def unmap(self, address, handler, *args, needs_reply_address=False):
except ValueError as e:
if str(e) == "list.remove(x): x not in list":
raise ValueError(
"Address '%s' doesn't have handler '%s' mapped to it"
% (address, handler)
f"Address '{address}' doesn't have handler '{handler}' mapped to it"
) from e

def handlers_for_address(
Expand All @@ -202,7 +201,7 @@ def handlers_for_address(
pattern = pattern.replace("\\*", "[\\w|\\+]*")
# The rest of the syntax in the specification is like the re module so
# we're fine.
pattern = pattern + "$"
pattern = f"{pattern}$"
patterncompiled = re.compile(pattern)
matched = False

Expand Down
6 changes: 3 additions & 3 deletions pythonosc/osc_bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def __init__(self, dgram: bytes) -> None:
try:
self._timestamp, index = osc_types.get_date(self._dgram, index)
except osc_types.ParseError as pe:
raise ParseError("Could not get the date from the datagram: %s" % pe)
raise ParseError(f"Could not get the date from the datagram: {pe}")
# Get the contents as a list of OscBundle and OscMessage.
self._contents = self._parse_contents(index)

Expand Down Expand Up @@ -61,10 +61,10 @@ def _parse_contents(
contents.append(osc_message.OscMessage(content_dgram))
else:
logging.warning(
"Could not identify content type of dgram %r" % content_dgram
f"Could not identify content type of dgram {content_dgram!r}"
)
except (osc_types.ParseError, osc_message.ParseError, IndexError) as e:
raise ParseError("Could not parse a content datagram: %s" % e)
raise ParseError(f"Could not parse a content datagram: {e}")

return contents

Expand Down
5 changes: 2 additions & 3 deletions pythonosc/osc_bundle_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,8 @@ def build(self) -> osc_bundle.OscBundle:
dgram += content.dgram
else:
raise BuildError(
"Content must be either OscBundle or OscMessage"
"found {}".format(type(content))
f"Content must be either OscBundle or OscMessage, found {type(content)}"
)
return osc_bundle.OscBundle(dgram)
except osc_types.BuildError as be:
raise BuildError("Could not build the bundle {}".format(be))
raise BuildError(f"Could not build the bundle {be}")
10 changes: 3 additions & 7 deletions pythonosc/osc_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,21 +73,17 @@ def _parse_datagram(self) -> None:
elif param == "]": # Array stop.
if len(param_stack) < 2:
raise ParseError(
"Unexpected closing bracket in type tag: {0}".format(
type_tag
)
f"Unexpected closing bracket in type tag: {type_tag}"
)
param_stack.pop()
# TODO: Support more exotic types as described in the specification.
else:
logging.warning("Unhandled parameter type: {0}".format(param))
logging.warning(f"Unhandled parameter type: {param}")
continue
if param not in "[]":
param_stack[-1].append(val)
if len(param_stack) != 1:
raise ParseError(
"Missing closing bracket in type tag: {0}".format(type_tag)
)
raise ParseError(f"Missing closing bracket in type tag: {type_tag}")
self._parameters = params
except osc_types.ParseError as pe:
raise ParseError("Found incorrect datagram, ignoring it", pe)
Expand Down
12 changes: 4 additions & 8 deletions pythonosc/osc_message_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,7 @@ def add_arg(self, arg_value: ArgValue, arg_type: Optional[str] = None) -> None:
"""
if arg_type and not self._valid_type(arg_type):
raise ValueError(
"arg_type must be one of {}, or an array of valid types".format(
self._SUPPORTED_ARG_TYPES
)
f"arg_type must be one of {self._SUPPORTED_ARG_TYPES}, or an array of valid types"
)
if not arg_type:
arg_type = self._get_arg_type(arg_value)
Expand Down Expand Up @@ -161,7 +159,7 @@ def build(self) -> osc_message.OscMessage:

# Write the parameters.
arg_types = "".join([arg[0] for arg in self._args])
dgram += osc_types.write_string("," + arg_types)
dgram += osc_types.write_string(f",{arg_types}")
for arg_type, value in self._args:
if arg_type == self.ARG_TYPE_STRING:
dgram += osc_types.write_string(value) # type: ignore[arg-type]
Expand All @@ -188,13 +186,11 @@ def build(self) -> osc_message.OscMessage:
):
continue
else:
raise BuildError(
"Incorrect parameter type found {}".format(arg_type)
)
raise BuildError(f"Incorrect parameter type found {arg_type}")

return osc_message.OscMessage(dgram)
except osc_types.BuildError as be:
raise BuildError("Could not build the message: {}".format(be))
raise BuildError(f"Could not build the message: {be}")


def build_msg(address: str, value: ArgValue = "") -> osc_message.OscMessage:
Expand Down
2 changes: 1 addition & 1 deletion pythonosc/osc_packet.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def __init__(self, dgram: bytes) -> None:
"OscBundle."
)
except (osc_bundle.ParseError, osc_message.ParseError) as pe:
raise ParseError("Could not parse packet %s" % pe)
raise ParseError(f"Could not parse packet {pe}")

@property
def messages(self) -> List[TimedMessage]:
Expand Down
34 changes: 17 additions & 17 deletions pythonosc/parsing/osc_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def write_string(val: str) -> bytes:
try:
dgram = val.encode("utf-8") # Default, but better be explicit.
except (UnicodeEncodeError, AttributeError) as e:
raise BuildError("Incorrect string, could not encode {}".format(e))
raise BuildError(f"Incorrect string, could not encode {e}")
diff = _STRING_DGRAM_PAD - (len(dgram) % _STRING_DGRAM_PAD)
dgram += b"\x00" * diff
return dgram
Expand Down Expand Up @@ -90,9 +90,9 @@ def get_string(dgram: bytes, start_index: int) -> Tuple[str, int]:
data_str = dgram[start_index : start_index + offset]
return data_str.replace(b"\x00", b"").decode("utf-8"), start_index + offset
except IndexError as ie:
raise ParseError("Could not parse datagram %s" % ie)
raise ParseError(f"Could not parse datagram {ie}")
except TypeError as te:
raise ParseError("Could not parse datagram %s" % te)
raise ParseError(f"Could not parse datagram {te}")


def write_int(val: int) -> bytes:
Expand All @@ -104,7 +104,7 @@ def write_int(val: int) -> bytes:
try:
return struct.pack(">i", val)
except struct.error as e:
raise BuildError("Wrong argument value passed: {}".format(e))
raise BuildError(f"Wrong argument value passed: {e}")


def get_int(dgram: bytes, start_index: int) -> Tuple[int, int]:
Expand All @@ -128,7 +128,7 @@ def get_int(dgram: bytes, start_index: int) -> Tuple[int, int]:
start_index + _INT_DGRAM_LEN,
)
except (struct.error, TypeError) as e:
raise ParseError("Could not parse datagram %s" % e)
raise ParseError(f"Could not parse datagram {e}")


def write_int64(val: int) -> bytes:
Expand All @@ -140,7 +140,7 @@ def write_int64(val: int) -> bytes:
try:
return struct.pack(">q", val)
except struct.error as e:
raise BuildError("Wrong argument value passed: {}".format(e))
raise BuildError(f"Wrong argument value passed: {e}")


def get_int64(dgram: bytes, start_index: int) -> Tuple[int, int]:
Expand All @@ -164,7 +164,7 @@ def get_int64(dgram: bytes, start_index: int) -> Tuple[int, int]:
start_index + _INT64_DGRAM_LEN,
)
except (struct.error, TypeError) as e:
raise ParseError("Could not parse datagram %s" % e)
raise ParseError(f"Could not parse datagram {e}")


def get_uint64(dgram: bytes, start_index: int) -> Tuple[int, int]:
Expand All @@ -190,7 +190,7 @@ def get_uint64(dgram: bytes, start_index: int) -> Tuple[int, int]:
start_index + _UINT64_DGRAM_LEN,
)
except (struct.error, TypeError) as e:
raise ParseError("Could not parse datagram %s" % e)
raise ParseError(f"Could not parse datagram {e}")


def get_timetag(dgram: bytes, start_index: int) -> Tuple[Tuple[datetime, int], int]:
Expand Down Expand Up @@ -223,7 +223,7 @@ def get_timetag(dgram: bytes, start_index: int) -> Tuple[Tuple[datetime, int], i

return (utc, fraction), start_index + _TIMETAG_DGRAM_LEN
except (struct.error, TypeError) as e:
raise ParseError("Could not parse datagram %s" % e)
raise ParseError(f"Could not parse datagram {e}")


def write_float(val: float) -> bytes:
Expand All @@ -235,7 +235,7 @@ def write_float(val: float) -> bytes:
try:
return struct.pack(">f", val)
except struct.error as e:
raise BuildError("Wrong argument value passed: {}".format(e))
raise BuildError(f"Wrong argument value passed: {e}")


def get_float(dgram: bytes, start_index: int) -> Tuple[float, int]:
Expand All @@ -262,7 +262,7 @@ def get_float(dgram: bytes, start_index: int) -> Tuple[float, int]:
start_index + _FLOAT_DGRAM_LEN,
)
except (struct.error, TypeError) as e:
raise ParseError("Could not parse datagram %s" % e)
raise ParseError(f"Could not parse datagram {e}")


def write_double(val: float) -> bytes:
Expand All @@ -274,7 +274,7 @@ def write_double(val: float) -> bytes:
try:
return struct.pack(">d", val)
except struct.error as e:
raise BuildError("Wrong argument value passed: {}".format(e))
raise BuildError(f"Wrong argument value passed: {e}")


def get_double(dgram: bytes, start_index: int) -> Tuple[float, int]:
Expand All @@ -300,7 +300,7 @@ def get_double(dgram: bytes, start_index: int) -> Tuple[float, int]:
start_index + _DOUBLE_DGRAM_LEN,
)
except (struct.error, TypeError) as e:
raise ParseError("Could not parse datagram {}".format(e))
raise ParseError(f"Could not parse datagram {e}")


def get_blob(dgram: bytes, start_index: int) -> Tuple[bytes, int]:
Expand Down Expand Up @@ -393,7 +393,7 @@ def write_rgba(val: bytes) -> bytes:
try:
return struct.pack(">I", val)
except struct.error as e:
raise BuildError("Wrong argument value passed: {}".format(e))
raise BuildError(f"Wrong argument value passed: {e}")


def get_rgba(dgram: bytes, start_index: int) -> Tuple[bytes, int]:
Expand All @@ -417,7 +417,7 @@ def get_rgba(dgram: bytes, start_index: int) -> Tuple[bytes, int]:
start_index + _INT_DGRAM_LEN,
)
except (struct.error, TypeError) as e:
raise ParseError("Could not parse datagram %s" % e)
raise ParseError(f"Could not parse datagram {e}")


def write_midi(val: MidiPacket) -> bytes:
Expand All @@ -435,7 +435,7 @@ def write_midi(val: MidiPacket) -> bytes:
value = sum((value & 0xFF) << 8 * (3 - pos) for pos, value in enumerate(val))
return struct.pack(">I", value)
except struct.error as e:
raise BuildError("Wrong argument value passed: {}".format(e))
raise BuildError(f"Wrong argument value passed: {e}")


def get_midi(dgram: bytes, start_index: int) -> Tuple[MidiPacket, int]:
Expand All @@ -460,4 +460,4 @@ def get_midi(dgram: bytes, start_index: int) -> Tuple[MidiPacket, int]:
)
return (midi_msg, start_index + _INT_DGRAM_LEN)
except (struct.error, TypeError) as e:
raise ParseError("Could not parse datagram %s" % e)
raise ParseError(f"Could not parse datagram {e}")
4 changes: 2 additions & 2 deletions scripts/print_datagrams_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ def main():
def _PrintOscMessages(ip, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((ip, port))
print("Listening for UDP packets on {0}:{1} ...".format(ip, port))
print(f"Listening for UDP packets on {ip}:{port} ...")
while True:
data, _ = sock.recvfrom(1024)
print("%s" % data)
print(f"{data}")


if __name__ == "__main__":
Expand Down
Loading