Skip to content

Commit d8b45c8

Browse files
kianelbodiemol
andauthored
[py] Change formatted strings to f-strings (#11087)
Change formatted strings to f-strings Co-authored-by: Diego Molina <[email protected]>
1 parent aa8d6cf commit d8b45c8

File tree

15 files changed

+57
-62
lines changed

15 files changed

+57
-62
lines changed

py/selenium/webdriver/common/action_chains.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ def scroll_from_origin(self, scroll_origin: ScrollOrigin, delta_x: int, delta_y:
361361
"""
362362

363363
if not isinstance(scroll_origin, ScrollOrigin):
364-
raise TypeError("Expected object of type ScrollOrigin, got: " "{}".format(type(scroll_origin)))
364+
raise TypeError(f"Expected object of type ScrollOrigin, got: {type(scroll_origin)}")
365365

366366
self.w3c_actions.wheel_action.scroll(
367367
origin=scroll_origin.origin,

py/selenium/webdriver/common/actions/pointer_input.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ class PointerInput(InputDevice):
3030
def __init__(self, kind, name):
3131
super().__init__()
3232
if kind not in POINTER_KINDS:
33-
raise InvalidArgumentException("Invalid PointerInput kind '%s'" % kind)
33+
raise InvalidArgumentException(f"Invalid PointerInput kind '{kind}'")
3434
self.type = POINTER
3535
self.kind = kind
3636
self.name = name

py/selenium/webdriver/common/bidi/cdp.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def __init__(self, obj):
150150
self.detail = obj.get("data")
151151

152152
def __str__(self):
153-
return "BrowserError<code={} message={}> {}".format(self.code, self.message, self.detail)
153+
return f"BrowserError<code={self.code} message={self.message}> {self.detail}"
154154

155155

156156
class CdpConnectionClosed(WsConnectionClosed):
@@ -261,7 +261,7 @@ def _handle_cmd_response(self, data):
261261
try:
262262
cmd, event = self.inflight_cmd.pop(cmd_id)
263263
except KeyError:
264-
logger.warning("Got a message with a command ID that does" " not exist: {}".format(data))
264+
logger.warning(f"Got a message with a command ID that does not exist: {data}")
265265
return
266266
if "error" in data:
267267
# If the server reported an error, convert it to an exception and do
@@ -440,7 +440,7 @@ async def _reader_task(self):
440440
try:
441441
session = self.sessions[session_id]
442442
except KeyError:
443-
raise BrowserError("Browser sent a message for an invalid " "session: {!r}".format(session_id))
443+
raise BrowserError(f"Browser sent a message for an invalid session: {session_id!r}")
444444
session._handle_data(data)
445445
else:
446446
self._handle_data(data)

py/selenium/webdriver/common/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,8 @@ def join_host_port(host: str, port: int) -> str:
9393
9494
"""
9595
if ":" in host and not host.startswith("["):
96-
return "[%s]:%d" % (host, port)
97-
return "%s:%d" % (host, port)
96+
return f"[{host}]:{port}"
97+
return f"{host}:{port}"
9898

9999

100100
def is_connectable(port: int, host: Optional[str] = "localhost") -> bool:
@@ -127,7 +127,7 @@ def is_url_connectable(port: Union[int, str]) -> bool:
127127
from urllib import request as url_request
128128

129129
try:
130-
res = url_request.urlopen("http://127.0.0.1:%s/status" % port)
130+
res = url_request.urlopen(f"http://127.0.0.1:{port}/status")
131131
return res.getcode() == 200
132132
except Exception:
133133
return False

py/selenium/webdriver/firefox/extension_connection.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def __init__(self, host, firefox_profile, firefox_binary=None, timeout=30):
5050
self.profile.add_extension()
5151

5252
self.binary.launch_browser(self.profile, timeout=timeout)
53-
_URL = "http://%s:%d/hub" % (HOST, PORT)
53+
_URL = f"http://{HOST}:{PORT}/hub"
5454
super().__init__(_URL, keep_alive=True)
5555

5656
def quit(self, sessionId=None):
@@ -66,7 +66,7 @@ def connect(self):
6666
@classmethod
6767
def connect_and_quit(cls):
6868
"""Connects to an running browser and quit immediately."""
69-
cls._request("%s/extensions/firefox/quit" % _URL)
69+
cls._request(f"{_URL}/extensions/firefox/quit")
7070

7171
@classmethod
7272
def is_connectable(cls):

py/selenium/webdriver/firefox/firefox_binary.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,8 +112,8 @@ def _wait_until_connectable(self, timeout=30):
112112
raise WebDriverException(
113113
"Can't load the profile. Possible firefox version mismatch. "
114114
"You must use GeckoDriver instead for Firefox 48+. Profile "
115-
"Dir: %s If you specified a log_file in the "
116-
"FirefoxBinary constructor, check it for details." % (self.profile.path)
115+
f"Dir: {self.profile.path} If you specified a log_file in the "
116+
"FirefoxBinary constructor, check it for details."
117117
)
118118
count += 1
119119
time.sleep(1)

py/selenium/webdriver/firefox/firefox_profile.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -195,8 +195,7 @@ def _read_existing_userjs(self, userjs):
195195
self.default_preferences[matches.group(1)] = json.loads(matches.group(2))
196196
except Exception:
197197
warnings.warn(
198-
"(skipping) failed to json.loads existing preference: %s" % matches.group(1)
199-
+ matches.group(2)
198+
f"(skipping) failed to json.loads existing preference: {matches.group(1) + matches.group(2)}"
200199
)
201200
except Exception:
202201
# The profile given hasn't had any changes made, i.e no users.js
@@ -233,7 +232,7 @@ def _install_extension(self, addon, unpack=True):
233232
# determine the addon id
234233
addon_details = self._addon_details(addon)
235234
addon_id = addon_details.get("id")
236-
assert addon_id, "The addon id could not be found: %s" % addon
235+
assert addon_id, f"The addon id could not be found: {addon}"
237236

238237
# copy the addon to the profile
239238
addon_path = os.path.join(self.extensionsDir, addon_id)
@@ -300,7 +299,7 @@ def parse_manifest_json(content):
300299
}
301300

302301
if not os.path.exists(addon_path):
303-
raise OSError("Add-on path does not exist: %s" % addon_path)
302+
raise OSError(f"Add-on path does not exist: {addon_path}")
304303

305304
try:
306305
if zipfile.is_zipfile(addon_path):
@@ -324,7 +323,7 @@ def parse_manifest_json(content):
324323
with open(os.path.join(addon_path, "install.rdf"), encoding="utf-8") as f:
325324
manifest = f.read()
326325
else:
327-
raise OSError("Add-on path is neither an XPI nor a directory: %s" % addon_path)
326+
raise OSError(f"Add-on path is neither an XPI nor a directory: {addon_path}")
328327
except (OSError, KeyError) as e:
329328
raise AddonFormatError(str(e), sys.exc_info()[2])
330329

py/selenium/webdriver/remote/errorhandler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ def check_response(self, response: Dict[str, Any]) -> None:
233233
file = f"{file}:{line}"
234234
meth = frame.get("methodName", "<anonymous>")
235235
if "className" in frame:
236-
meth = "{}.{}".format(frame["className"], meth)
236+
meth = f"{frame['className']}.{meth}"
237237
msg = " at %s (%s)"
238238
msg = msg % (meth, file)
239239
stacktrace.append(msg)

py/selenium/webdriver/remote/remote_connection.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def get_remote_connection_headers(cls, parsed_url, keep_alive=False):
110110
}
111111

112112
if parsed_url.username:
113-
base64string = b64encode("{0.username}:{0.password}".format(parsed_url).encode())
113+
base64string = b64encode(f"{parsed_url.username}:{parsed_url.password}".encode())
114114
headers.update({"Authorization": f"Basic {base64string.decode()}"})
115115

116116
if keep_alive:
@@ -285,7 +285,7 @@ def execute(self, command, params):
285285
its JSON payload.
286286
"""
287287
command_info = self._commands[command]
288-
assert command_info is not None, "Unrecognised command %s" % command
288+
assert command_info is not None, f"Unrecognised command {command}"
289289
path = string.Template(command_info[1]).substitute(params)
290290
if isinstance(params, dict) and "sessionId" in params:
291291
del params["sessionId"]

py/selenium/webdriver/remote/shadowroot.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,26 +43,26 @@ def __repr__(self) -> str:
4343
def find_element(self, by: str = By.ID, value: str = None):
4444
if by == By.ID:
4545
by = By.CSS_SELECTOR
46-
value = '[id="%s"]' % value
46+
value = f'[id="{value}"]'
4747
elif by == By.CLASS_NAME:
4848
by = By.CSS_SELECTOR
49-
value = ".%s" % value
49+
value = f".{value}"
5050
elif by == By.NAME:
5151
by = By.CSS_SELECTOR
52-
value = '[name="%s"]' % value
52+
value = f'[name="{value}"]'
5353

5454
return self._execute(Command.FIND_ELEMENT_FROM_SHADOW_ROOT, {"using": by, "value": value})["value"]
5555

5656
def find_elements(self, by: str = By.ID, value: str = None):
5757
if by == By.ID:
5858
by = By.CSS_SELECTOR
59-
value = '[id="%s"]' % value
59+
value = f'[id="{value}"]'
6060
elif by == By.CLASS_NAME:
6161
by = By.CSS_SELECTOR
62-
value = ".%s" % value
62+
value = f".{value}"
6363
elif by == By.NAME:
6464
by = By.CSS_SELECTOR
65-
value = '[name="%s"]' % value
65+
value = f'[name="{value}"]'
6666

6767
return self._execute(Command.FIND_ELEMENTS_FROM_SHADOW_ROOT, {"using": by, "value": value})["value"]
6868

0 commit comments

Comments
 (0)