Skip to content

Conversation

@sourcery-ai
Copy link

@sourcery-ai sourcery-ai bot commented Oct 23, 2023

Branch main refactored by Sourcery.

If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.

See our documentation here.

Run Sourcery locally

Reduce the feedback loop during development by using the Sourcery editor plugin:

Review changes via command line

To manually merge these changes, make sure you're on the main branch, then run:

git fetch origin sourcery/main
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

@sourcery-ai sourcery-ai bot requested a review from Powerm4 October 23, 2023 16:27
Copy link
Author

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery timed out performing refactorings.

Due to GitHub API limits, only the first 60 comments can be shown.

# General substitutions.
project = 'Python'
copyright = '2001-%s, Python Software Foundation' % time.strftime('%Y')
copyright = f"2001-{time.strftime('%Y')}, Python Software Foundation"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 52-378 refactored with the following changes:

This removes the following comments ( why? ):

# The font size ('10pt', '11pt' or '12pt').
# The paper size ('letter' or 'a4').
# Additional stuff for the LaTeX preamble.

# If obj does not have a persistent ID, return None. This means obj
# needs to be pickled as usual.
return None
return ("MemoRecord", obj.key) if isinstance(obj, MemoRecord) else None
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DBPickler.persistent_id refactored with the following changes:

This removes the following comments ( why? ):

# If obj does not have a persistent ID, return None. This means obj
# key, which refers to a specific record in the database.
# Here, our persistent ID is simply a tuple, containing a tag and a
# needs to be pickled as usual.

Comment on lines -19 to +25
print('To: {}'.format(headers['to']))
print('From: {}'.format(headers['from']))
print('Subject: {}'.format(headers['subject']))
print(f"To: {headers['to']}")
print(f"From: {headers['from']}")
print(f"Subject: {headers['subject']}")

# You can also access the parts of the addresses:
print('Recipient username: {}'.format(headers['to'].addresses[0].username))
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))
print(f"Recipient username: {headers['to'].addresses[0].username}")
print(f"Sender name: {headers['from'].addresses[0].display_name}")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 19-25 refactored with the following changes:

Comment on lines -46 to +67
if richest['content-type'].maintype == 'text':
if richest['content-type'].subtype == 'plain':
for line in richest.get_content().splitlines():
print(line)
sys.exit()
elif richest['content-type'].subtype == 'html':
body = richest
else:
print("Don't know how to display {}".format(richest.get_content_type()))
sys.exit()
elif richest['content-type'].content_type == 'multipart/related':
if (
richest['content-type'].maintype == 'text'
and richest['content-type'].subtype == 'plain'
):
for line in richest.get_content().splitlines():
print(line)
sys.exit()
elif (
richest['content-type'].maintype == 'text'
and richest['content-type'].subtype == 'html'
):
body = richest
elif (
richest['content-type'].maintype == 'text'
or richest['content-type'].content_type != 'multipart/related'
):
print(f"Don't know how to display {richest.get_content_type()}")
sys.exit()
else:
body = richest.get_body(preferencelist=('html'))
for part in richest.iter_attachments():
fn = part.get_filename()
if fn:
if fn := part.get_filename():
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 46-70 refactored with the following changes:

for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
rc = [node.data for node in nodelist if node.nodeType == node.TEXT_NODE]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function getText refactored with the following changes:

Comment on lines -122 to +111
if self.dst(dt):
return self.dstname
else:
return self.stdname
return self.dstname if self.dst(dt) else self.stdname
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function USTimeZone.tzname refactored with the following changes:

line_numbers = list(itertools.chain(*line_ranges))

return line_numbers
return list(itertools.chain(*line_ranges))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_diff_lines refactored with the following changes:

Comment on lines -126 to +124
non_null_matches = [warning for warning in warning_matches if warning]
return non_null_matches
return [warning for warning in warning_matches if warning]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function filter_and_parse_warnings refactored with the following changes:

Comment on lines -146 to -151
warnings_touched = [
return [
warning
for warning in warnings_infile
if int(warning["line"]) in touched_para_lines
]
return warnings_touched
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function filter_warnings_by_diff refactored with the following changes:

Comment on lines -175 to +171
warnings_touched = warnings_added + list(
itertools.chain(*warnings_modified_touched)
)

return warnings_touched
return warnings_added + list(itertools.chain(*warnings_modified_touched))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function process_touched_warnings refactored with the following changes:

Comment on lines -218 to +210
problem_files = sorted(should_be_clean & files_with_nits)
if problem_files:
if problem_files := sorted(should_be_clean & files_with_nits):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fail_if_regression refactored with the following changes:

Comment on lines -238 to +229
files_with_no_nits = files_with_expected_nits - files_with_nits
if files_with_no_nits:
if files_with_no_nits := files_with_expected_nits - files_with_nits:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fail_if_improved refactored with the following changes:

Comment on lines 13 to +14


Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 29-32 refactored with the following changes:

refcount = None
else:
refcount = int(refcount)
refcount = None if not refcount or refcount == "null" else int(refcount)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Annotations.__init__ refactored with the following changes:

Comment on lines -113 to +110
# Stable ABI annotation. These have two forms:
# Part of the [Stable ABI](link).
# Part of the [Stable ABI](link) since version X.Y.
# For structs, there's some more info in the message:
# Part of the [Limited API](link) (as an opaque struct).
# Part of the [Stable ABI](link) (including all members).
# Part of the [Limited API](link) (Only some members are part
# of the stable ABI.).
# ... all of which can have "since version X.Y" appended.
record = self.stable_abi_data.get(name)
if record:
if record := self.stable_abi_data.get(name):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Annotations.add_annotations refactored with the following changes:

This removes the following comments ( why? ):

#   Part of the [Limited API](link) (as an opaque struct).
#   Part of the [Stable ABI](link) since version X.Y.
# Stable ABI annotation. These have two forms:
# ... all of which can have "since version X.Y" appended.
# Stable ABI was introduced in 3.2.
# For structs, there's some more info in the message:
#   Part of the [Stable ABI](link) (including all members).
#   Part of the [Stable ABI](link).
#       of the stable ABI.).
#   Part of the [Limited API](link) (Only some members are part

Comment on lines -561 to +562
f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
f.write((f'topics = {pformat(self.topics)}' + '\n').encode('utf-8'))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function PydocTopicsBuilder.finish refactored with the following changes:

Comment on lines -606 to +607
signode += addnodes.desc_addname(' '+args, ' '+args)
signode += addnodes.desc_addname(f' {args}', f' {args}')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_pdb_command refactored with the following changes:

Comment on lines -664 to +667
ref = nodes.reference("", nodes.Text("[{}]".format(i)), internal=True)
ref = nodes.reference("", nodes.Text(f"[{i}]"), internal=True)
try:
ref['refuri'] = "{}#{}".format(
app.builder.get_relative_uri(fromdocname, doc),
label,
)
ref['refuri'] = f"{app.builder.get_relative_uri(fromdocname, doc)}#{label}"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function process_audit_events refactored with the following changes:

return "_Feature" + repr((self.optional,
self.mandatory,
self.compiler_flag))
return f"_Feature{repr((self.optional, self.mandatory, self.compiler_flag))}"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _Feature.__repr__ refactored with the following changes:

Comment on lines -15 to +21
fp = open("/tmp/_aix_support.%s"%(
os.getpid(),), "w+b")
fp = open(f"/tmp/_aix_support.{os.getpid()}", "w+b")

with contextlib.closing(fp) as fp:
if capture_stderr:
cmd = "%s >'%s' 2>&1" % (commandstring, fp.name)
cmd = f"{commandstring} >'{fp.name}' 2>&1"
else:
cmd = "%s 2>/dev/null >'%s'" % (commandstring, fp.name)
cmd = f"{commandstring} 2>/dev/null >'{fp.name}'"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _read_cmd_output refactored with the following changes:

Comment on lines -88 to -92
# type: () -> List[int]
gnu_type = sysconfig.get_config_var("BUILD_GNU_TYPE")
if not gnu_type:
if gnu_type := sysconfig.get_config_var("BUILD_GNU_TYPE"):
return _aix_vrtl(vrmf=gnu_type)
else:
raise ValueError("BUILD_GNU_TYPE is not defined")
return _aix_vrtl(vrmf=gnu_type)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _aix_bgt refactored with the following changes:

This removes the following comments ( why? ):

# type: () -> List[int]

if cls is Hashable:
return _check_methods(C, "__hash__")
return NotImplemented
return _check_methods(C, "__hash__") if cls is Hashable else NotImplemented
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Hashable.__subclasshook__ refactored with the following changes:

Comment on lines -141 to +139
if cls is Awaitable:
return _check_methods(C, "__await__")
return NotImplemented
return _check_methods(C, "__await__") if cls is Awaitable else NotImplemented
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Awaitable.__subclasshook__ refactored with the following changes:

Comment on lines -290 to +286
if cls is Iterable:
return _check_methods(C, "__iter__")
return NotImplemented
return _check_methods(C, "__iter__") if cls is Iterable else NotImplemented
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Iterable.__subclasshook__ refactored with the following changes:

Comment on lines -409 to +403
if cls is Sized:
return _check_methods(C, "__len__")
return NotImplemented
return _check_methods(C, "__len__") if cls is Sized else NotImplemented
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Sized.__subclasshook__ refactored with the following changes:

rawdata = self.rawdata
nlines = rawdata.count("\n", i, j)
if nlines:
if nlines := rawdata.count("\n", i, j):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ParserBase.updatepos refactored with the following changes:

Comment on lines -113 to -116
m = _declstringlit_match(rawdata, j)
if not m:
if m := _declstringlit_match(rawdata, j):
j = m.end()
else:
return -1 # incomplete
j = m.end()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ParserBase.parse_declaration refactored with the following changes:

Comment on lines -215 to +214
meth = getattr(self, "_parse_doctype_" + name)
meth = getattr(self, f"_parse_doctype_{name}")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ParserBase._parse_doctype_subset refactored with the following changes:

Comment on lines -255 to +253
if '>' in rawdata[j:]:
return rawdata.find(">", j) + 1
return -1
return rawdata.find(">", j) + 1 if '>' in rawdata[j:] else -1
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ParserBase._parse_doctype_element refactored with the following changes:

Comment on lines -294 to +290
m = _declstringlit_match(rawdata, j)
if m:
if m := _declstringlit_match(rawdata, j):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ParserBase._parse_doctype_attlist refactored with the following changes:

Copy link

@code-review-doctor code-review-doctor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Worth considering though. View full project report here.

# https://xkcd.com/426/
h = hashlib.md5(datedow, usedforsecurity=False).hexdigest()
p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])]
p, q = ['%f' % float.fromhex(f'0.{x}') for x in (h[:16], h[16:32])]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

f-string is easier to read, write, and less computationally expensive than legacy string formatting. More details.

parts.append('%*s%s\n' % (help_position, '', line))

# or add a newline if the description doesn't end with one
parts.extend('%*s%s\n' % (help_position, '', line) for line in help_lines[1:])

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

f-string is easier to read, write, and less computationally expensive than legacy string formatting. Read more.

result = '[%s [%s ...]]' % metavar
else:
result = '[%s ...]' % metavar
return '[%s [%s ...]]' % metavar if len(metavar) == 2 else f'[{metavar} ...]'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As above, Consider using f-string instead.

return '[%s [%s ...]]' % metavar if len(metavar) == 2 else f'[{metavar} ...]'
elif action.nargs == ONE_OR_MORE:
result = '%s [%s ...]' % get_metavar(2)
return '%s [%s ...]' % get_metavar(2)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise, Consider using f-string instead.

return '&#%d;' % codepoint
else:
return '&%s;' % name
return '&#%d;' % codepoint if name is None else f'&{name};'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

f-string is easier to read, write, and less computationally expensive than legacy string formatting. More.

lines.append("Free variables:")
for i_n in enumerate(co.co_freevars):
lines.append("%4d: %s" % i_n)
lines.extend("%4d: %s" % i_n for i_n in enumerate(co.co_freevars))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above: Consider using f-string instead.

lines.append("Cell variables:")
for i_n in enumerate(co.co_cellvars):
lines.append("%4d: %s" % i_n)
lines.extend("%4d: %s" % i_n for i_n in enumerate(co.co_cellvars))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarly, Consider using f-string instead.

return "<flag %r>" % cls.__name__
def __repr__(self):
if Flag is not None and issubclass(self, Flag):
return "<flag %r>" % self.__name__

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

f-string is easier to read, write, and less computationally expensive than legacy string formatting. Explained here.

return "<flag %r>" % self.__name__
else:
return "<enum %r>" % cls.__name__
return "<enum %r>" % self.__name__

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise, Consider using f-string instead.

if self._name_ is not None:
return self._name_
cls_name = self.__class__.__name__
return "%s(%r)" % (cls_name, self._value_)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, Consider using f-string instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant