Skip to content

Commit

Permalink
Fix errors reported by the ruff flake8-comprehensions (C4) plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
nsoranzo committed Jul 15, 2024
1 parent 20dea74 commit 7650ae6
Show file tree
Hide file tree
Showing 35 changed files with 71 additions and 82 deletions.
6 changes: 2 additions & 4 deletions lib/bx/align/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,9 +312,7 @@ def reverse_complement(self):
if self.empty:
text = None
else:
comp = [ch for ch in self.text.translate(DNA_COMP)]
comp.reverse()
text = "".join(comp)
text = self.text.translate(DNA_COMP)[::-1]
new = Component(self.src, start, self.size, strand, self._src_size, text)
if self.empty:
new.empty = True
Expand Down Expand Up @@ -386,7 +384,7 @@ def coord_to_col(self, pos):
if pos < start or pos > end:
raise ValueError("Range error: %d not in %d-%d" % (pos, start, end))
if not self.index:
self.index = list()
self.index = []
if self.strand == "-":
# nota bene: for - strand self.index[x] maps to one column
# higher than is actually associated with the position; thus
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/align/lav.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ def write(self, alignment):
self.block += 1

def close(self):
keys = [key for key in self.blockHash]
keys = list(self.blockHash)
keys = sort_keys_by_chrom(keys)
for key in keys:
(src1, strand1, src2, strand2) = key
Expand Down
6 changes: 3 additions & 3 deletions lib/bx/align/score.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ def __init__(
if gap2 is None:
gap2 = gap1 # (scheme with gap1=gap2=None is legit)
if isinstance(alphabet1, str):
alphabet1 = [ch for ch in alphabet1]
alphabet1 = list(alphabet1)
if isinstance(alphabet2, str):
alphabet2 = [ch for ch in alphabet2]
alphabet2 = list(alphabet2)
self.table = ones((text1_range, text2_range), typecode)
self.table *= default
self.gap_open = gap_open
Expand Down Expand Up @@ -143,7 +143,7 @@ def read_scoring_scheme(f, gap_open, gap_extend, gap1="-", gap2=None, **kwargs):
if isinstance(f, str):
f = open(f)
close_it = True
ss = build_scoring_scheme("".join([line for line in f]), gap_open, gap_extend, gap1=gap1, gap2=gap2, **kwargs)
ss = build_scoring_scheme("".join(list(f)), gap_open, gap_extend, gap1=gap1, gap2=gap2, **kwargs)
if close_it:
f.close()
return ss
Expand Down
4 changes: 2 additions & 2 deletions lib/bx/align/sitemask/cpg.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,13 @@ def __call__(self, block):


def mask_columns(masklist, text, mask):
templist = list()
templist = []
for position in masklist:
if text[position] != "-":
templist.append(position)
templist.append(len(text)) # Add the end of the text
# cut string
newtext = list()
newtext = []
c = 0
for position in templist:
newtext.append(text[c:position])
Expand Down
8 changes: 4 additions & 4 deletions lib/bx/bitset_builders.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def binned_bitsets_from_file(
"""
last_chrom = None
last_bitset = None
bitsets = dict()
bitsets = {}
for line in f:
if line.startswith("#") or line.isspace():
continue
Expand Down Expand Up @@ -68,7 +68,7 @@ def binned_bitsets_from_bed_file(
"""
last_chrom = None
last_bitset = None
bitsets = dict()
bitsets = {}
offset = 0
for line in f:
if line.startswith("#") or line.isspace():
Expand Down Expand Up @@ -108,7 +108,7 @@ def binned_bitsets_proximity(f, chrom_col=0, start_col=1, end_col=2, strand_col=
"""Read a file into a dictionary of bitsets"""
last_chrom = None
last_bitset = None
bitsets = dict()
bitsets = {}
for line in f:
if line.startswith("#"):
continue
Expand Down Expand Up @@ -143,7 +143,7 @@ def binned_bitsets_from_list(list=[]):
"""Read a list into a dictionary of bitsets"""
last_chrom = None
last_bitset = None
bitsets = dict()
bitsets = {}
for l in list:
chrom = l[0]
if chrom != last_chrom:
Expand Down
10 changes: 5 additions & 5 deletions lib/bx/cookbook/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,15 +304,15 @@ def _format_usage(self, usage, actions, groups, prefix):

# if usage is specified, use that
if usage is not None:
usage = usage % dict(prog=self._prog)
usage = usage % {"prog": self._prog}

# if no optionals or positionals are available, usage is just prog
elif usage is None and not actions:
usage = "%(prog)s" % dict(prog=self._prog)
usage = "%(prog)s" % {"prog": self._prog}

# if optionals and positionals are available, calculate usage
elif usage is None:
prog = "%(prog)s" % dict(prog=self._prog)
prog = "%(prog)s" % {"prog": self._prog}

# split optionals from positionals
optionals = []
Expand Down Expand Up @@ -486,7 +486,7 @@ def _format_actions_usage(self, actions, groups):

def _format_text(self, text):
if "%(prog)" in text:
text = text % dict(prog=self._prog)
text = text % {"prog": self._prog}
text_width = self._width - self._current_indent
indent = " " * self._current_indent
return self._fill_text(text, text_width, indent) + "\n\n"
Expand Down Expand Up @@ -704,7 +704,7 @@ def __str__(self):
format = "%(message)s"
else:
format = "argument %(argument_name)s: %(message)s"
return format % dict(message=self.message, argument_name=self.argument_name)
return format % {"message": self.message, "argument_name": self.argument_name}


class ArgumentTypeError(Exception):
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/cookbook/doc_optparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def parse(docstring, arglist=None):
action = "store"
k = k.split("=")[0]
opt_strings.append(k)
p.add_option(*opt_strings, **dict(action=action, help=help.strip()))
p.add_option(*opt_strings, **{"action": action, "help": help.strip()})
except (IndexError, ValueError):
raise ParsingError("Cannot parse the option string correctly")
return p.parse_args(arglist)
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def __call__(self, block):

class Pipeline(Filter):
def __init__(self, **kwargs):
self.pipeline = list()
self.pipeline = []

def __call__(self, block):
for function in self.pipeline:
Expand Down
8 changes: 4 additions & 4 deletions lib/bx/interval_index_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def new_indexed_access(self, data_filename, index_filename=None, keep_open=False
return self.indexed_access_class(data_filename, index_filename, keep_open, **kwargs)

def get(self, src, start, end):
return [block for block in self.get_as_iterator(src, start, end)]
return list(self.get_as_iterator(src, start, end))

def get_as_iterator(self, src, start, end):
for block, _index, _offset in self.get_as_iterator_with_index_and_offset(src, start, end):
Expand Down Expand Up @@ -257,7 +257,7 @@ def open_data(self):
return f

def get(self, src, start, end):
return [val for val in self.get_as_iterator(src, start, end)]
return list(self.get_as_iterator(src, start, end))

def get_as_iterator(self, src, start, end):
for val, _index, _offset in self.get_as_iterator_with_index_and_offset(src, start, end):
Expand Down Expand Up @@ -287,7 +287,7 @@ class Indexes:
"""A set of indexes, each identified by a unique name"""

def __init__(self, filename=None):
self.indexes = dict()
self.indexes = {}
if filename is not None:
self.open(filename)

Expand All @@ -312,7 +312,7 @@ def find(self, name, start, end):

def open(self, filename):
self.filename = filename
self.offsets = dict() # (will map key to (offset,value_size))
self.offsets = {} # (will map key to (offset,value_size))
with open(filename, "rb") as f:
magic, version, length = read_packed(f, ">3I")
if magic != MAGIC:
Expand Down
6 changes: 3 additions & 3 deletions lib/bx/intervals/cluster_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def test_large_sorted(self):
pairs = [(2 * i + 1, 2 * i + 2) for i in range(upto)]
self.insertpairs(pairs)
self.tree.insert(0, upto * 3, upto)
self.assertEqual([(0, upto * 3, [x for x in range(upto + 1)])], self.tree.getregions())
self.assertEqual([(0, upto * 3, list(range(upto + 1)))], self.tree.getregions())

def test_minregions(self):
self.tree = ClusterTree(0, 2)
Expand Down Expand Up @@ -92,7 +92,7 @@ def test_larger(self):
]
self.insertpairs(pairs)

self.assertEqual([(1, 20, [x for x in range(14)]), (21, 22, [14])], self.tree.getregions())
self.assertEqual([(1, 20, list(range(14))), (21, 22, [14])], self.tree.getregions())

def test_another(self):
pairs = [
Expand All @@ -116,7 +116,7 @@ def test_another(self):
for s, e, i in pairs:
self.tree.insert(s, e, i)

self.assertEqual([(1, 20, [x for x in range(14)]), (21, 22, [14])], self.tree.getregions())
self.assertEqual([(1, 20, list(range(14))), (21, 22, [14])], self.tree.getregions())

def test_none(self):
pairs = []
Expand Down
8 changes: 4 additions & 4 deletions lib/bx/intervals/intersection_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,13 +160,13 @@ def setUp(self):
iv = IntervalTree()
n = 0
for i in range(1, 1000, 80):
iv.insert(i, i + 10, dict(value=i * i))
iv.insert(i, i + 10, {"value": i * i})
# add is synonym for insert.
iv.add(i + 20, i + 30, dict(astr=str(i * i)))
iv.add(i + 20, i + 30, {"astr": str(i * i)})

# or insert/add an interval object with start, end attrs.
iv.insert_interval(Interval(i + 40, i + 50, value=dict(astr=str(i * i))))
iv.add_interval(Interval(i + 60, i + 70, value=dict(astr=str(i * i))))
iv.insert_interval(Interval(i + 40, i + 50, value={"astr": str(i * i)}))
iv.add_interval(Interval(i + 60, i + 70, value={"astr": str(i * i)}))

n += 4
self.intervals = self.iv = iv
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/intervals/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def binned_bitsets(self, upstream_pad=0, downstream_pad=0, lens=None):
lens = {}
last_chrom = None
last_bitset = None
bitsets = dict()
bitsets = {}
for interval in self:
if isinstance(interval, GenomicInterval):
chrom = interval[self.chrom_col]
Expand Down
4 changes: 2 additions & 2 deletions lib/bx/intervals/operations/find_clusters.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@


def find_clusters(reader, mincols=1, minregions=2):
extra = dict()
chroms = dict()
extra = {}
chroms = {}
linenum = -1
for interval in reader:
linenum += 1
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/intervals/operations/join.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def report_unvisited(node, results):
results = []
rightTree.traverse(lambda x: report_unvisited(x, results))
for item in results:
outfields = list()
outfields = []
for x in range(leftlen):
outfields.append(".")
outfields.extend(item.other)
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/misc/seekbzip2.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def readable(self):
return True

def readlines(self, sizehint=-1):
return [ln for ln in self]
return list(self)

def seekable(self):
return True
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/pwm/position_weight_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def __init__(self, id, rows, alphabet, background=None, score_correction=True):

# scale counts to integers
for i in range(len(rows)):
hashRows.append(dict())
hashRows.append({})
for x, sym in enumerate(alphabet):
(w, s) = rows[i][x]
hashRows[i][sym] = w * scale / s
Expand Down
13 changes: 3 additions & 10 deletions lib/bx/pwm/pwm_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,11 @@
class PWMTestCase(unittest.TestCase):
def testReader(self):
# test basic format: i.e. for jaspar
wms = [
wm for wm in pwm.Reader(StringIO(basicPwm), format="basic", background=background, score_correction=False)
]
wms = list(pwm.Reader(StringIO(basicPwm), format="basic", background=background, score_correction=False))
assert len(wms) == 1

# test transfac format
wms = [
wm
for wm in pwm.Reader(
StringIO(transfacPwm), format="transfac", background=background, score_correction=False
)
]
wms = list(pwm.Reader(StringIO(transfacPwm), format="transfac", background=background, score_correction=False))
assert len(wms) == 1

wm = wms[0]
Expand All @@ -87,7 +80,7 @@ def testReader(self):

qdSeq = []
for ix, nt in enumerate(dSeq):
qdSeq.append(dict())
qdSeq.append({})
qdSeq[ix][nt] = 1.0
qScores = wm.score_seq(qdSeq)
assert len(qScores) == 2
Expand Down
4 changes: 1 addition & 3 deletions lib/bx/seq/seq.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,7 @@ def raw_fetch(self, start, length):
return self.text[start : start + length]

def reverse_complement(self, text):
comp = [ch for ch in text.translate(DNA_COMP)]
comp.reverse()
return "".join(comp)
return text.translate(DNA_COMP)[::-1]


class SeqReader:
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/seq/twobit.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def __init__(self, file: BinaryIO, do_mask: bool = True):
# Header contains some reserved space
self.reserved = self.read("L")
# Read index of sequence names to offsets
index: Dict[str, TwoBitSequence] = dict()
index: Dict[str, TwoBitSequence] = {}
for _ in range(self.seq_count):
name = self.read_p_string()
offset = self.read("L")
Expand Down
14 changes: 7 additions & 7 deletions lib/bx_extras/pyparsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ def __init__(self, toklist, name=None, asList=True, modal=True):
self.__toklist = toklist[:]
else:
self.__toklist = [toklist]
self.__tokdict = dict()
self.__tokdict = {}

# this line is related to debugging the asXML bug
# ~ asList = False
Expand Down Expand Up @@ -355,13 +355,13 @@ def __getitem__(self, i):

def __setitem__(self, k, v):
if isinstance(v, _ParseResultsWithOffset):
self.__tokdict[k] = self.__tokdict.get(k, list()) + [v]
self.__tokdict[k] = self.__tokdict.get(k, []) + [v]
sub = v[0]
elif isinstance(k, int):
self.__toklist[k] = v
sub = v
else:
self.__tokdict[k] = self.__tokdict.get(k, list()) + [_ParseResultsWithOffset(v, 0)]
self.__tokdict[k] = self.__tokdict.get(k, []) + [_ParseResultsWithOffset(v, 0)]
sub = v
if isinstance(sub, ParseResults):
sub.__parent = wkref(self)
Expand Down Expand Up @@ -698,7 +698,7 @@ def setDefaultWhitespaceChars(chars):
setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars)

def __init__(self, savelist=False):
self.parseAction = list()
self.parseAction = []
self.failAction = None
# ~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall
self.strRepr = None
Expand All @@ -709,7 +709,7 @@ def __init__(self, savelist=False):
self.copyDefaultWhiteChars = True
self.mayReturnEmpty = False # used when checking for left-recursion
self.keepTabs = False
self.ignoreExprs = list()
self.ignoreExprs = []
self.debug = False
self.streamlined = False
self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index
Expand Down Expand Up @@ -2585,7 +2585,7 @@ def parseImpl(self, instring, loc, doActions=True):
raise ParseException(instring, loc, "Missing one or more required elements (%s)" % missing)

# add any unmatched Optionals, in case they have default values defined
matchOrder += list(e for e in self.exprs if isinstance(e, Optional) and e.expr in tmpOpt)
matchOrder += [e for e in self.exprs if isinstance(e, Optional) and e.expr in tmpOpt]

resultlist = []
for e in matchOrder:
Expand Down Expand Up @@ -3531,7 +3531,7 @@ def withAttribute(*args, **attrDict):
attrs = args[:]
else:
attrs = attrDict.items()
attrs = [(k, v) for k, v in attrs]
attrs = list(attrs)

def pa(s, l, tokens):
for attrName, attrValue in attrs:
Expand Down
Loading

0 comments on commit 7650ae6

Please sign in to comment.