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

15 files changed

+57
-62
lines changed

py/selenium/webdriver/common/action_chains.py

+1-1
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

+1-1
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

+3-3
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

+3-3
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

+2-2
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

+2-2
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

+4-5
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

+1-1
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

+2-2
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

+6-6
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

py/selenium/webdriver/remote/webdriver.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ def __init__(
288288
self.start_session(capabilities, browser_profile)
289289

290290
def __repr__(self):
291-
return '<{0.__module__}.{0.__name__} (session="{1}")>'.format(type(self), self.session_id)
291+
return f'<{type(self).__module__}.{type(self).__name__} (session="{self.session_id}")>'
292292

293293
def __enter__(self):
294294
return self
@@ -850,13 +850,13 @@ def find_element(self, by=By.ID, value: Optional[str] = None) -> WebElement:
850850

851851
if by == By.ID:
852852
by = By.CSS_SELECTOR
853-
value = '[id="%s"]' % value
853+
value = f'[id="{value}"]'
854854
elif by == By.CLASS_NAME:
855855
by = By.CSS_SELECTOR
856-
value = ".%s" % value
856+
value = f".{value}"
857857
elif by == By.NAME:
858858
by = By.CSS_SELECTOR
859-
value = '[name="%s"]' % value
859+
value = f'[name="{value}"]'
860860

861861
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
862862

@@ -879,13 +879,13 @@ def find_elements(self, by=By.ID, value: Optional[str] = None) -> List[WebElemen
879879

880880
if by == By.ID:
881881
by = By.CSS_SELECTOR
882-
value = '[id="%s"]' % value
882+
value = f'[id="{value}"]'
883883
elif by == By.CLASS_NAME:
884884
by = By.CSS_SELECTOR
885-
value = ".%s" % value
885+
value = f".{value}"
886886
elif by == By.NAME:
887887
by = By.CSS_SELECTOR
888-
value = '[name="%s"]' % value
888+
value = f'[name="{value}"]'
889889

890890
# Return empty list if driver returns null
891891
# See https://github.com/SeleniumHQ/selenium/issues/4555

py/selenium/webdriver/remote/webelement.py

+6-10
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,7 @@ def __init__(self, parent, id_):
7474
self._id = id_
7575

7676
def __repr__(self):
77-
return '<{0.__module__}.{0.__name__} (session="{1}", element="{2}")>'.format(
78-
type(self), self._parent.session_id, self._id
79-
)
77+
return f'<{type(self).__module__}.{type(self).__name__} (session="{self._parent.session_id}", element="{self._id}")>'
8078

8179
@property
8280
def tag_name(self) -> str:
@@ -176,9 +174,7 @@ def get_attribute(self, name) -> str:
176174
"""
177175
if getAttribute_js is None:
178176
_load_js()
179-
attribute_value = self.parent.execute_script(
180-
"return (%s).apply(null, arguments);" % getAttribute_js, self, name
181-
)
177+
attribute_value = self.parent.execute_script(f"return ({getAttribute_js}).apply(null, arguments);", self, name)
182178
return attribute_value
183179

184180
def is_selected(self) -> bool:
@@ -261,7 +257,7 @@ def is_displayed(self) -> bool:
261257
# Only go into this conditional for browsers that don't use the atom themselves
262258
if isDisplayed_js is None:
263259
_load_js()
264-
return self.parent.execute_script("return (%s).apply(null, arguments);" % isDisplayed_js, self)
260+
return self.parent.execute_script(f"return ({isDisplayed_js}).apply(null, arguments);", self)
265261

266262
@property
267263
def location_once_scrolled_into_view(self) -> dict:
@@ -422,13 +418,13 @@ def find_element(self, by=By.ID, value=None) -> WebElement:
422418
"""
423419
if by == By.ID:
424420
by = By.CSS_SELECTOR
425-
value = '[id="%s"]' % value
421+
value = f'[id="{value}"]'
426422
elif by == By.CLASS_NAME:
427423
by = By.CSS_SELECTOR
428-
value = ".%s" % value
424+
value = f".{value}"
429425
elif by == By.NAME:
430426
by = By.CSS_SELECTOR
431-
value = '[name="%s"]' % value
427+
value = f'[name="{value}"]'
432428

433429
return self._execute(Command.FIND_CHILD_ELEMENT, {"using": by, "value": value})["value"]
434430

py/selenium/webdriver/support/color.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -150,11 +150,11 @@ def __init__(self, red: ParseableInt, green: ParseableInt, blue: ParseableInt, a
150150

151151
@property
152152
def rgb(self) -> str:
153-
return "rgb(%d, %d, %d)" % (self.red, self.green, self.blue)
153+
return f"rgb({self.red}, {self.green}, {self.blue})"
154154

155155
@property
156156
def rgba(self) -> str:
157-
return "rgba(%d, %d, %d, %s)" % (self.red, self.green, self.blue, self.alpha)
157+
return f"rgba({self.red}, {self.green}, {self.blue}, {self.alpha})"
158158

159159
@property
160160
def hex(self) -> str:
@@ -175,7 +175,7 @@ def __hash__(self) -> int:
175175
return hash((self.red, self.green, self.blue, self.alpha))
176176

177177
def __repr__(self) -> str:
178-
return "Color(red=%d, green=%d, blue=%d, alpha=%s)" % (self.red, self.green, self.blue, self.alpha)
178+
return f"Color(red={self.red}, green={self.green}, blue={self.blue}, alpha={self.alpha})"
179179

180180
def __str__(self) -> str:
181181
return f"Color: {self.rgba}"

0 commit comments

Comments
 (0)