Skip to content

Commit 3f6717d

Browse files
marksmayosymonk
andauthored
pylint fixes including tidy of f strings, simplifications of conditional statements and isinstances (#11205)
pylint fixes Tidying up of a bunch of pylint issues Co-authored-by: Simon K <[email protected]>
1 parent 484359c commit 3f6717d

File tree

13 files changed

+60
-65
lines changed

13 files changed

+60
-65
lines changed

py/generate.py

Lines changed: 25 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -106,12 +106,11 @@ def escape_backticks(docstr):
106106
def replace_one(match):
107107
if match.group(2) == 's':
108108
return f"``{match.group(1)}``'s"
109-
elif match.group(2):
109+
if match.group(2):
110110
# This case (some trailer other than "s") doesn't currently exist
111111
# in the CDP definitions, but it's here just to be safe.
112112
return f'``{match.group(1)}`` {match.group(2)}'
113-
else:
114-
return f'``{match.group(1)}``'
113+
return f'``{match.group(1)}``'
115114

116115
# Sometimes pipes are used where backticks should have been used.
117116
docstr = docstr.replace('|', '`')
@@ -179,17 +178,15 @@ def get_annotation(cls, cdp_type):
179178
''' Return a type annotation for the CDP type. '''
180179
if cdp_type == 'any':
181180
return 'typing.Any'
182-
else:
183-
return cls[cdp_type].value
181+
return cls[cdp_type].value
184182

185183
@classmethod
186184
def get_constructor(cls, cdp_type, val):
187185
''' Return the code to construct a value for a given CDP type. '''
188186
if cdp_type == 'any':
189187
return val
190-
else:
191-
cons = cls[cdp_type].value
192-
return f'{cons}({val})'
188+
cons = cls[cdp_type].value
189+
return f'{cons}({val})'
193190

194191

195192
@dataclass
@@ -333,18 +330,17 @@ def from_json(cls, type_):
333330
type_['type'],
334331
CdpItems.from_json(type_['items']) if 'items' in type_ else None,
335332
type_.get('enum'),
336-
[CdpProperty.from_json(p) for p in type_.get('properties', list())],
333+
[CdpProperty.from_json(p) for p in type_.get('properties', [])],
337334
)
338335

339336
def generate_code(self):
340337
''' Generate Python code for this type. '''
341338
logger.debug('Generating type %s: %s', self.id, self.type)
342339
if self.enum:
343340
return self.generate_enum_code()
344-
elif self.properties:
341+
if self.properties:
345342
return self.generate_class_code()
346-
else:
347-
return self.generate_primitive_code()
343+
return self.generate_primitive_code()
348344

349345
def generate_primitive_code(self):
350346
''' Generate code for a primitive type. '''
@@ -395,7 +391,7 @@ def generate_enum_code(self):
395391
def to_json(self):
396392
return self.value''')
397393

398-
def_from_json = dedent(f'''\
394+
def_from_json = dedent('''\
399395
@classmethod
400396
def from_json(cls, json):
401397
return cls(json)''')
@@ -449,12 +445,12 @@ def to_json(self):
449445

450446
# Emit from_json() method. The properties are sorted in the same order
451447
# as above for readability.
452-
def_from_json = dedent(f'''\
448+
def_from_json = dedent('''\
453449
@classmethod
454450
def from_json(cls, json):
455451
return cls(
456452
''')
457-
from_jsons = list()
453+
from_jsons = []
458454
for p in props:
459455
from_json = p.generate_from_json(dict_='json')
460456
from_jsons.append(f'{p.py_name}={from_json},')
@@ -526,10 +522,10 @@ def generate_doc(self):
526522
doc = f':param {self.py_name}:'
527523

528524
if self.experimental:
529-
doc += f' **(EXPERIMENTAL)**'
525+
doc += ' **(EXPERIMENTAL)**'
530526

531527
if self.optional:
532-
doc += f' *(Optional)*'
528+
doc += ' *(Optional)*'
533529

534530
if self.description:
535531
desc = self.description.replace('`', '``').replace('\n', ' ')
@@ -600,8 +596,8 @@ def py_name(self):
600596
@classmethod
601597
def from_json(cls, command, domain) -> 'CdpCommand':
602598
''' Instantiate a CDP command from a JSON object. '''
603-
parameters = command.get('parameters', list())
604-
returns = command.get('returns', list())
599+
parameters = command.get('parameters', [])
600+
returns = command.get('returns', [])
605601

606602
return cls(
607603
command['name'],
@@ -653,7 +649,7 @@ def generate_code(self):
653649
if self.description:
654650
doc = self.description
655651
if self.experimental:
656-
doc += f'\n\n**EXPERIMENTAL**'
652+
doc += '\n\n**EXPERIMENTAL**'
657653
if self.parameters and doc:
658654
doc += '\n\n'
659655
elif not self.parameters and self.returns:
@@ -735,7 +731,7 @@ def from_json(cls, json: dict, domain: str):
735731
json.get('deprecated', False),
736732
json.get('experimental', False),
737733
[typing.cast(CdpParameter, CdpParameter.from_json(p))
738-
for p in json.get('parameters', list())],
734+
for p in json.get('parameters', [])],
739735
domain
740736
)
741737

@@ -804,16 +800,16 @@ def module(self):
804800
@classmethod
805801
def from_json(cls, domain: dict):
806802
''' Instantiate a CDP domain from a JSON object. '''
807-
types = domain.get('types', list())
808-
commands = domain.get('commands', list())
809-
events = domain.get('events', list())
803+
types = domain.get('types', [])
804+
commands = domain.get('commands', [])
805+
events = domain.get('events', [])
810806
domain_name = domain['domain']
811807

812808
return cls(
813809
domain_name,
814810
domain.get('description'),
815811
domain.get('experimental', False),
816-
domain.get('dependencies', list()),
812+
domain.get('dependencies', []),
817813
[CdpType.from_json(type) for type in types],
818814
[CdpCommand.from_json(command, domain_name)
819815
for command in commands],
@@ -939,12 +935,12 @@ def parse(json_path, output_path):
939935
:returns: a list of CDP domain objects
940936
'''
941937
global current_version
942-
with open(json_path) as json_file:
938+
with open(json_path, encoding="utf-8") as json_file:
943939
schema = json.load(json_file)
944940
version = schema['version']
945941
assert (version['major'], version['minor']) == ('1', '3')
946942
current_version = f'{version["major"]}.{version["minor"]}'
947-
domains = list()
943+
domains = []
948944
for domain in schema['domains']:
949945
domains.append(CdpDomain.from_json(domain))
950946
return domains
@@ -957,7 +953,7 @@ def generate_init(init_path, domains):
957953
:param list[tuple] modules: a list of modules each represented as tuples
958954
of (name, list_of_exported_symbols)
959955
'''
960-
with open(init_path, "w") as init_file:
956+
with open(init_path, "w", encoding="utf-8") as init_file:
961957
init_file.write(INIT_HEADER)
962958
for domain in domains:
963959
init_file.write(f'from . import {domain.module}\n')
@@ -1001,7 +997,7 @@ def main(browser_protocol_path, js_protocol_path, output_path):
1001997
subpath.unlink()
1002998

1003999
# Parse domains
1004-
domains = list()
1000+
domains = []
10051001
for json_path in json_paths:
10061002
logger.info('Parsing JSON file %s', json_path)
10071003
domains.extend(parse(json_path, output_path))

py/selenium/webdriver/chromium/webdriver.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def __init__(
7474
DeprecationWarning,
7575
stacklevel=2,
7676
)
77-
if keep_alive != DEFAULT_KEEP_ALIVE and type(self) == __class__:
77+
if keep_alive != DEFAULT_KEEP_ALIVE and isinstance(self, __class__):
7878
warnings.warn(
7979
"keep_alive has been deprecated, please pass in a Service object", DeprecationWarning, stacklevel=2
8080
)

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,8 @@ def __init__(self, ws, session_id, target_id):
194194
self.target_id = target_id
195195
self.channels = defaultdict(set)
196196
self.id_iter = itertools.count()
197-
self.inflight_cmd = dict()
198-
self.inflight_result = dict()
197+
self.inflight_cmd = {}
198+
self.inflight_result = {}
199199

200200
async def execute(self, cmd: typing.Generator[dict, T, typing.Any]) -> T:
201201
"""Execute a command on the server and wait for the result.
@@ -384,7 +384,7 @@ def __init__(self, ws):
384384
:param trio_websocket.WebSocketConnection ws:
385385
"""
386386
super().__init__(ws, session_id=None, target_id=None)
387-
self.sessions = dict()
387+
self.sessions = {}
388388

389389
async def aclose(self):
390390
"""Close the underlying WebSocket connection.

py/selenium/webdriver/common/service.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,12 +209,11 @@ def _start_process(self, path: str) -> None:
209209
raise WebDriverException(
210210
f"'{os.path.basename(self.path)}' executable needs to be in PATH. {self.start_error_message}"
211211
)
212-
elif err.errno == errno.EACCES:
212+
if err.errno == errno.EACCES:
213213
raise WebDriverException(
214214
f"'{os.path.basename(self.path)}' executable may have wrong permissions. {self.start_error_message}"
215215
)
216-
else:
217-
raise
216+
raise
218217
except Exception as e:
219218
raise WebDriverException(
220219
f"The executable {os.path.basename(self.path)} needs to be available in the path. {self.start_error_message}\n{str(e)}"

py/selenium/webdriver/remote/webdriver.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1202,7 +1202,7 @@ def get_credentials(self) -> List[Credential]:
12021202
def remove_credential(self, credential_id: Union[str, bytearray]) -> None:
12031203
"""Removes a credential from the authenticator."""
12041204
# Check if the credential is bytearray converted to b64 string
1205-
if type(credential_id) is bytearray:
1205+
if isinstance(credential_id, bytearray):
12061206
credential_id = urlsafe_b64encode(credential_id).decode()
12071207

12081208
self.execute(

py/selenium/webdriver/remote/webelement.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ def shadow_root(self) -> ShadowRoot:
247247
"safari",
248248
], "This only currently works in Chromium based browsers"
249249
assert (
250-
not browser_main_version <= 95
250+
browser_main_version > 95
251251
), f"Please use Chromium based browsers with version 96 or later. Version used {self._parent.caps['browserVersion']}"
252252
return self._execute(Command.GET_SHADOW_ROOT)["value"]
253253

py/test/runner/run_pytest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
import pytest
1919

20-
with open("pytest.ini", "w") as ini_file:
20+
with open("pytest.ini", "w", encoding="utf-8") as ini_file:
2121
ini_file.write("[pytest]\n")
2222
ini_file.write("addopts = -r=a\n")
2323
ini_file.write("rootdir = py\n")

py/test/selenium/webdriver/chrome/proxy_tests.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def test_bad_proxy_doesnt_interfere():
3636

3737
assert hasattr(driver, "command_executor")
3838
assert hasattr(driver.command_executor, "_proxy_url")
39-
assert type(driver.command_executor._conn) == urllib3.PoolManager
39+
assert isinstance(driver.command_executor._conn, urllib3.PoolManager)
4040
os.environ.pop("https_proxy")
4141
os.environ.pop("http_proxy")
4242
driver.quit()

py/test/selenium/webdriver/common/executing_async_javascript_tests.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def reset_timeouts(driver):
3333
def test_should_not_timeout_if_callback_invoked_immediately(driver, pages):
3434
pages.load("ajaxy_page.html")
3535
result = driver.execute_async_script("arguments[arguments.length - 1](123);")
36-
assert type(result) == int
36+
assert isinstance(result, int)
3737
assert 123 == result
3838

3939

@@ -55,15 +55,15 @@ def test_should_be_able_to_return_an_array_literal_from_an_async_script(driver,
5555
pages.load("ajaxy_page.html")
5656
result = driver.execute_async_script("arguments[arguments.length - 1]([]);")
5757
assert "Expected not to be null!", result is not None
58-
assert type(result) == list
58+
assert isinstance(result, list)
5959
assert len(result) == 0
6060

6161

6262
def test_should_be_able_to_return_an_array_object_from_an_async_script(driver, pages):
6363
pages.load("ajaxy_page.html")
6464
result = driver.execute_async_script("arguments[arguments.length - 1](new Array());")
6565
assert "Expected not to be null!", result is not None
66-
assert type(result) == list
66+
assert isinstance(result, list)
6767
assert len(result) == 0
6868

6969

@@ -73,7 +73,7 @@ def test_should_be_able_to_return_arrays_of_primitives_from_async_scripts(driver
7373
result = driver.execute_async_script("arguments[arguments.length - 1]([null, 123, 'abc', true, false]);")
7474

7575
assert result is not None
76-
assert type(result) == list
76+
assert isinstance(result, list)
7777
assert not bool(result.pop())
7878
assert bool(result.pop())
7979
assert "abc" == result.pop()
@@ -96,7 +96,7 @@ def test_should_be_able_to_return_arrays_of_web_elements_from_async_scripts(driv
9696

9797
result = driver.execute_async_script("arguments[arguments.length - 1]([document.body, document.body]);")
9898
assert result is not None
99-
assert type(result) == list
99+
assert isinstance(result, list)
100100

101101
list_ = result
102102
assert 2 == len(list_)

py/test/selenium/webdriver/common/executing_javascript_tests.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,15 @@ def test_should_be_able_to_execute_simple_javascript_and_return_astring(driver,
3232

3333
result = driver.execute_script("return document.title")
3434

35-
assert type(result) == str, "The type of the result is %s" % type(result)
35+
assert isinstance(result, str), "The type of the result is %s" % type(result)
3636
assert "XHTML Test Page" == result
3737

3838

3939
def test_should_be_able_to_execute_simple_javascript_and_return_an_integer(driver, pages):
4040
pages.load("nestedElements.html")
4141
result = driver.execute_script("return document.getElementsByName('checky').length")
4242

43-
assert type(result) == int
43+
assert isinstance(result, int)
4444
assert int(result) > 1
4545

4646

@@ -124,7 +124,7 @@ def test_should_be_able_to_execute_simple_javascript_and_return_aboolean(driver,
124124
result = driver.execute_script("return true")
125125

126126
assert result is not None
127-
assert type(result) == bool
127+
assert isinstance(result, bool)
128128
assert bool(result)
129129

130130

@@ -149,23 +149,23 @@ def test_should_be_able_to_execute_simple_javascript_and_return_an_array(driver,
149149
expectedResult.append(subList)
150150
result = driver.execute_script("return ['zero', [true, false]]")
151151
assert result is not None
152-
assert type(result) == list
152+
assert isinstance(result, list)
153153
assert expectedResult == result
154154

155155

156156
def test_passing_and_returning_an_int_should_return_awhole_number(driver, pages):
157157
pages.load("javascriptPage.html")
158158
expectedResult = 1
159159
result = driver.execute_script("return arguments[0]", expectedResult)
160-
assert type(result) == int
160+
assert isinstance(result, int)
161161
assert expectedResult == result
162162

163163

164164
def test_passing_and_returning_adouble_should_return_adecimal(driver, pages):
165165
pages.load("javascriptPage.html")
166166
expectedResult = 1.2
167167
result = driver.execute_script("return arguments[0]", expectedResult)
168-
assert type(result) == float
168+
assert isinstance(result, float)
169169
assert expectedResult == result
170170

171171

0 commit comments

Comments
 (0)