Simplify looping across Gramps.

Index based loops across the Gramps project
are mapped to their Pythonic equalivant.

Many of these improves radability, and a
some of them improves performance by being
lazy evaluated.
This commit is contained in:
Baizley 2019-12-21 12:13:04 +01:00 committed by Nick Hall
parent 8777c11811
commit 7248f073f0
44 changed files with 121 additions and 172 deletions

View File

@ -255,8 +255,7 @@ class ArgParser:
# Some args can work on a list of databases: # Some args can work on a list of databases:
if leftargs: if leftargs:
for opt_ix in range(len(options)): for option, value in options:
option, value = options[opt_ix]
if option in ['-L', '-l', '-t']: if option in ['-L', '-l', '-t']:
self.database_names = leftargs self.database_names = leftargs
leftargs = [] leftargs = []
@ -269,8 +268,7 @@ class ArgParser:
) % leftargs[0], ) % leftargs[0],
file=sys.stderr) file=sys.stderr)
#see if force open is on #see if force open is on
for opt_ix in range(len(options)): for option, value in options:
option, value = options[opt_ix]
if option in ('-u', '--force-unlock'): if option in ('-u', '--force-unlock'):
self.force_unlock = True self.force_unlock = True
break break
@ -279,8 +277,7 @@ class ArgParser:
# Go over all given option and place them into appropriate lists # Go over all given option and place them into appropriate lists
cleandbg = [] cleandbg = []
need_to_quit = False need_to_quit = False
for opt_ix in range(len(options)): for opt_ix, (option, value) in enumerate(options):
option, value = options[opt_ix]
if option in ['-O', '--open']: if option in ['-O', '--open']:
self.open = value self.open = value
elif option in ['-C', '--create']: elif option in ['-C', '--create']:
@ -345,10 +342,9 @@ class ArgParser:
from gramps.gen.config import config from gramps.gen.config import config
print(_("Gramps config settings from %s:" print(_("Gramps config settings from %s:"
) % config.filename) ) % config.filename)
for sect in config.data: for sect, settings in config.data.items():
for setting in config.data[sect]: for setting, value in settings.items():
print("%s.%s=%s" % (sect, setting, print("%s.%s=%s" % (sect, setting, repr(value)))
repr(config.data[sect][setting])))
print() print()
sys.exit(0) sys.exit(0)
elif option in ['-c', '--config']: elif option in ['-c', '--config']:
@ -438,8 +434,7 @@ class ArgParser:
sys.exit(0) # Done with Default sys.exit(0) # Done with Default
#clean options list #clean options list
cleandbg.reverse() for ind in reversed(cleandbg):
for ind in cleandbg:
del options[ind] del options[ind]
if (len(options) > 0 if (len(options) > 0

View File

@ -94,6 +94,9 @@ class TestArgParser(unittest.TestCase):
argument_parser.errors argument_parser.errors
) )
def test_option_with_multiple_arguments(self):
argument_parser = self.create_parser('-l', 'family_tree_name')
self.assertEqual(argument_parser.database_names, ['family_tree_name'])
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@ -2008,8 +2008,7 @@ class DbWriteBase(DbReadBase):
birth_ref_index = -1 birth_ref_index = -1
death_ref_index = -1 death_ref_index = -1
event_ref_list = person.get_event_ref_list() event_ref_list = person.get_event_ref_list()
for index in range(len(event_ref_list)): for index, ref in enumerate(event_ref_list):
ref = event_ref_list[index]
event = self.get_event_from_handle(ref.ref) event = self.get_event_from_handle(ref.ref)
if (event.type.is_birth() if (event.type.is_birth()
and ref.role.is_primary() and ref.role.is_primary()

View File

@ -53,8 +53,8 @@ class ParamFilter(GenericFilter):
# Need to change existing params one by one to keep # Need to change existing params one by one to keep
# the correct number of arguments # the correct number of arguments
new_list = rule.list[:] new_list = rule.list[:]
for ix in range(len(self.param_list)): for index, param in enumerate(self.param_list):
new_list[ix] = self.param_list[ix] new_list[index] = param
rule.set_list(new_list) rule.set_list(new_list)
for rule in self.flist: for rule in self.flist:
if rule.nrprepare > 0: if rule.nrprepare > 0:

View File

@ -81,7 +81,7 @@ class Rule:
if self.nrprepare == 0: if self.nrprepare == 0:
if self.use_regex: if self.use_regex:
self.regex = [None]*len(self.labels) self.regex = [None]*len(self.labels)
for i in range(len(self.labels)): for i in enumerate(self.labels):
if self.list[i]: if self.list[i]:
try: try:
self.regex[i] = re.compile(self.list[i], re.I) self.regex[i] = re.compile(self.list[i], re.I)
@ -141,10 +141,10 @@ class Rule:
def display_values(self): def display_values(self):
"""Return the labels and values of this rule.""" """Return the labels and values of this rule."""
l_v = ('%s="%s"' % (_(self.labels[ix][0] if l_v = ('%s="%s"' % (_(self.labels[index][0] if
isinstance(self.labels[ix], tuple) else isinstance(self.labels[index], tuple) else
self.labels[ix]), self.list[ix]) self.labels[index]), item)
for ix in range(len(self.list)) if self.list[ix]) for index, item in enumerate(self.list) if item)
return ';'.join(l_v) return ';'.join(l_v)

View File

@ -235,7 +235,7 @@ class ParserDateTest(BaseDateTest):
Date displayer and parser tests. Date displayer and parser tests.
""" """
def do_case(self, testset): def do_case(self, testset):
for date_format in range(len(get_date_formats())): for date_format in enumerate(get_date_formats()):
set_format(date_format) set_format(date_format)
for dateval in date_tests[testset]: for dateval in date_tests[testset]:

View File

@ -300,9 +300,7 @@ def string_trim(font, text, width, ellipses = "..."):
# find the part that is < width # find the part that is < width
retval = "" retval = ""
sumlen = 0 sumlen = 0
length = 0 for c in text:
for i in range(len(text)):
c = text[i]
try: try:
length = l[ord(c)] length = l[ord(c)]
except: except:
@ -325,9 +323,7 @@ def string_trim(font, text, width, ellipses = "..."):
# too long; try again with ellipses # too long; try again with ellipses
retval = "" retval = ""
sumlen = 0 sumlen = 0
length = 0 for c in text:
for i in range(len(text)):
c = text[i]
try: try:
length = l[ord(c)] length = l[ord(c)]
except: except:

View File

@ -516,10 +516,9 @@ class BookList:
'length="%d">\n' % ( 'length="%d">\n' % (
escape(option_name), escape(option_name),
len(options[option_name]))) len(options[option_name])))
for list_index in range(len(option_value)): for list_index, v in enumerate(option_value):
option_type = type_name( option_type = type_name(v)
option_value[list_index]) value = escape(str(v))
value = escape(str(option_value[list_index]))
value = value.replace('"', '&quot;') value = value.replace('"', '&quot;')
b_f.write(' <listitem number="%d" ' b_f.write(' <listitem number="%d" '
'type="%s" value="%s"/>\n' % ( 'type="%s" value="%s"/>\n' % (
@ -557,7 +556,7 @@ class BookList:
b_f.write(' <size value="%f %f"/>' b_f.write(' <size value="%f %f"/>'
'\n' % (size[0], size[1])) '\n' % (size[0], size[1]))
if book.get_margins(): if book.get_margins():
for pos in range(len(book.get_margins())): for pos in enumerate(book.get_margins()):
b_f.write(' <margin number="%s" ' b_f.write(' <margin number="%s" '
'value="%f"/>\n' % ( 'value="%f"/>\n' % (
pos, book.get_margin(pos))) pos, book.get_margin(pos)))

View File

@ -497,7 +497,7 @@ class OptionListCollection(_options.OptionListCollection):
% (size[0], size[1])) % (size[0], size[1]))
if option_list.get_margins(): if option_list.get_margins():
margins = option_list.get_margins() margins = option_list.get_margins()
for pos in range(len(margins)): for pos in enumerate(margins):
file.write(' <margin number="%s" value="%f"/>\n' file.write(' <margin number="%s" value="%f"/>\n'
% (pos, margins[pos])) % (pos, margins[pos]))

View File

@ -107,10 +107,10 @@ def roman(num):
nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L',
'XL', 'X', 'IX', 'V', 'IV', 'I') 'XL', 'X', 'IX', 'V', 'IV', 'I')
retval = "" retval = ""
for i in range(len(vals)): for i, value in enumerate(vals):
amount = int(num / vals[i]) amount = int(num / value)
retval += nums[i] * amount retval += nums[i] * amount
num -= vals[i] * amount num -= value * amount
return retval return retval
#------------------------------------------------------------------------- #-------------------------------------------------------------------------

View File

@ -151,45 +151,25 @@ class RecentFiles:
""" """
Rename a file in the recent files list. Rename a file in the recent files list.
""" """
# First we need to walk the existing items to see for recent_file in self.gramps_recent_files:
# if our item is already there if recent_file.get_name() == filename:
found = False recent_file.set_name(new_filename)
for index in range(len(self.gramps_recent_files)):
if self.gramps_recent_files[index].get_name() == filename:
# Found it -- break here and change that item
found = True
break break
if found:
self.gramps_recent_files[index].set_name(new_filename)
def remove_filename(self, filename): def remove_filename(self, filename):
""" """
Remove a file from the recent files list. Remove a file from the recent files list.
""" """
# First we need to walk the existing items to see for index, recent_file in enumerate(self.gramps_recent_files):
# if our item is already there if recent_file.get_name() == filename:
found = False self.gramps_recent_files.pop(index)
for index in range(len(self.gramps_recent_files)):
if self.gramps_recent_files[index].get_name() == filename:
# Found it -- break here and pop that item
found = True
break break
if found:
self.gramps_recent_files.pop(index)
def check_if_recent(self, filename): def check_if_recent(self, filename):
""" """
Check if a file is present in the recent files list. Check if a file is present in the recent files list.
""" """
# First we need to walk the existing items to see return any(filename == recent_file.get_name() for recent_file in self.gramps_recent_files)
# if our item is already there
found = False
for index in range(len(self.gramps_recent_files)):
if self.gramps_recent_files[index].get_name() == filename:
# Found it -- break here and pop that item
found = True
break
return found
def save(self): def save(self):
""" """
@ -213,9 +193,7 @@ class RecentFiles:
fcntl.lockf(xml_file, fcntl.LOCK_EX) fcntl.lockf(xml_file, fcntl.LOCK_EX)
xml_file.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") xml_file.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
xml_file.write('<RecentFiles>\n') xml_file.write('<RecentFiles>\n')
index = 0 for index, item in enumerate(self.gramps_recent_files):
for item in self.gramps_recent_files:
index += 1
if index > MAX_GRAMPS_ITEMS: if index > MAX_GRAMPS_ITEMS:
break break
xml_file.write(' <RecentItem>\n') xml_file.write(' <RecentItem>\n')

View File

@ -70,7 +70,7 @@ class SimpleTable:
Set the columns Set the columns
""" """
self._columns = [str(col) for col in cols] self._columns = [str(col) for col in cols]
self._sort_vals = [[] for i in range(len(self._columns))] self._sort_vals = [[] for i in self._columns]
def row_sort_val(self, col, val): def row_sort_val(self, col, val):
""" """
@ -93,8 +93,7 @@ class SimpleTable:
retval = [] retval = []
row = len(self._rows) row = len(self._rows)
self._raw_data.append([]) self._raw_data.append([])
for col in range(len(data)): for col, item in enumerate(data):
item = data[col]
self._raw_data[-1].append(item) self._raw_data[-1].append(item)
# FIXME: add better text representations of these objects # FIXME: add better text representations of these objects
if item is None: if item is None:

View File

@ -234,7 +234,7 @@ class GalleryTab(ButtonTab, DbGUIElement):
while node is not None: while node is not None:
newlist.append(self.iconmodel.get_value(node, 2)) newlist.append(self.iconmodel.get_value(node, 2))
node = self.iconmodel.iter_next(node) node = self.iconmodel.iter_next(node)
for i in range(len(self.media_list)): for i in self.media_list:
self.media_list.pop() self.media_list.pop()
for i in newlist: for i in newlist:
if i: if i:

View File

@ -186,7 +186,7 @@ class SurnameTab(EmbeddedList):
the model the model
""" """
new_list = [] new_list = []
for idx in range(len(self.model)): for idx in enumerate(self.model):
node = self.model.get_iter(idx) node = self.model.get_iter(idx)
surn = self.model.get_value(node, 5) surn = self.model.get_value(node, 5)
surn.set_prefix(self.model.get_value(node, 0)) surn.set_prefix(self.model.get_value(node, 0))
@ -318,7 +318,7 @@ class SurnameTab(EmbeddedList):
#obtain current value #obtain current value
node = self.model.get_iter(path) node = self.model.get_iter(path)
old_val = self.model.get_value(node, colnr) old_val = self.model.get_value(node, colnr)
for nr in range(len(self.obj.get_surname_list())): for nr in enumerate(self.obj.get_surname_list()):
if nr == int(path[0]): if nr == int(path[0]):
if old_val: if old_val:
#True remains True #True remains True

View File

@ -141,15 +141,15 @@ class EditDate(ManagedWindow):
self.calendar_box.connect('changed', self.switch_calendar) self.calendar_box.connect('changed', self.switch_calendar)
self.quality_box = self.top.get_object('quality_box') self.quality_box = self.top.get_object('quality_box')
for item_number in range(len(QUAL_TEXT)): for item_number, item in enumerate(QUAL_TEXT):
self.quality_box.append_text(QUAL_TEXT[item_number][1]) self.quality_box.append_text(item[1])
if self.date.get_quality() == QUAL_TEXT[item_number][0]: if self.date.get_quality() == item[0]:
self.quality_box.set_active(item_number) self.quality_box.set_active(item_number)
self.type_box = self.top.get_object('type_box') self.type_box = self.top.get_object('type_box')
for item_number in range(len(MOD_TEXT)): for item_number, item in enumerate(MOD_TEXT):
self.type_box.append_text(MOD_TEXT[item_number][1]) self.type_box.append_text(item[1])
if self.date.get_modifier() == MOD_TEXT[item_number][0]: if self.date.get_modifier() == item[0]:
self.type_box.set_active(item_number) self.type_box.set_active(item_number)
self.type_box.connect('changed', self.switch_type) self.type_box.connect('changed', self.switch_type)

View File

@ -988,8 +988,7 @@ class EditPerson(EditPrimary):
inorder = True inorder = True
prev_date = 0 prev_date = 0
handle_list = [ref.ref for ref in child_ref_list] handle_list = [ref.ref for ref in child_ref_list]
for i in range(len(handle_list)): for child_handle in handle_list:
child_handle = handle_list[i]
child = self.db.get_person_from_handle(child_handle) child = self.db.get_person_from_handle(child_handle)
if child.get_birth_ref(): if child.get_birth_ref():
event_handle = child.get_birth_ref().ref event_handle = child.get_birth_ref().ref

View File

@ -547,8 +547,7 @@ class ExportAssistant(ManagedWindow, Gtk.Assistant):
selected one. selected one.
""" """
for ix in range(len(self.format_buttons)): for ix, button in enumerate(self.format_buttons):
button = self.format_buttons[ix]
if button.get_active(): if button.get_active():
return ix return ix
return 0 return 0

View File

@ -221,8 +221,8 @@ class CommandLineTool:
vals = self.options_help[self.show][2] vals = self.options_help[self.show][2]
if isinstance(vals, (list, tuple)): if isinstance(vals, (list, tuple)):
if self.options_help[self.show][3]: if self.options_help[self.show][3]:
for num in range(len(vals)): for num, value in enumerate(vals):
print(" %d\t%s" % (num, vals[num])) print(" %d\t%s" % (num, value))
else: else:
for val in vals: for val in vals:
print(" %s" % val) print(" %s" % val)

View File

@ -149,7 +149,7 @@ class BaseSelector(ManagedWindow):
parent_path = self.model.get_path(parent_iter) parent_path = self.model.get_path(parent_iter)
if parent_path: if parent_path:
parent_path_list = parent_path.get_indices() parent_path_list = parent_path.get_indices()
for i in range(len(parent_path_list)): for i in enumerate(parent_path_list):
expand_path = Gtk.TreePath( expand_path = Gtk.TreePath(
tuple([x for x in parent_path_list[:i+1]])) tuple([x for x in parent_path_list[:i+1]]))
self.tree.expand_row(expand_path, False) self.tree.expand_row(expand_path, False)
@ -165,8 +165,7 @@ class BaseSelector(ManagedWindow):
def add_columns(self,tree): def add_columns(self,tree):
tree.set_fixed_height_mode(True) tree.set_fixed_height_mode(True)
titles = self.get_column_titles() titles = self.get_column_titles()
for ix in range(len(titles)): for ix, item in enumerate(titles):
item = titles[ix]
if item[2] == BaseSelector.NONE: if item[2] == BaseSelector.NONE:
continue continue
elif item[2] == BaseSelector.TEXT: elif item[2] == BaseSelector.TEXT:
@ -302,7 +301,7 @@ class BaseSelector(ManagedWindow):
#sorting arrow in column header (not on start, only on click) #sorting arrow in column header (not on start, only on click)
if not self.setupcols : if not self.setupcols :
for i in range(len(self.columns)): for i in enumerate(self.columns):
enable_sort_flag = (i==self.sort_col) enable_sort_flag = (i==self.sort_col)
self.columns[i].set_sort_indicator(enable_sort_flag) self.columns[i].set_sort_indicator(enable_sort_flag)
self.columns[self.sort_col].set_sort_order(self.sortorder) self.columns[self.sort_col].set_sort_order(self.sortorder)

View File

@ -275,9 +275,9 @@ class UIManager():
parent = self.et_xml.find(".//*[@id='%s'].." % el_id) parent = self.et_xml.find(".//*[@id='%s'].." % el_id)
if parent: if parent:
# we found it, now delete original, inset updated # we found it, now delete original, inset updated
for indx in range(len(parent)): for indx, p in enumerate(parent):
if parent[indx].get('id') == el_id: if p.get('id') == el_id:
del parent[indx] del p
parent.insert(indx, update) parent.insert(indx, update)
else: else:
# updated item not present in original, just add it # updated item not present in original, just add it
@ -314,7 +314,7 @@ class UIManager():
# find parent of id'd element # find parent of id'd element
element = self.et_xml.find(".//*[@id='%s']" % el_id) element = self.et_xml.find(".//*[@id='%s']" % el_id)
if element: # element may have already been deleted if element: # element may have already been deleted
for dummy in range(len(element)): for dummy in element:
del element[0] del element[0]
#results = ET.tostring(self.et_xml, encoding="unicode") #results = ET.tostring(self.et_xml, encoding="unicode")
#LOG.info(results) #LOG.info(results)

View File

@ -423,7 +423,7 @@ class ListView(NavigationView):
parent_path = self.model.get_path(parent_iter) parent_path = self.model.get_path(parent_iter)
if parent_path: if parent_path:
parent_path_list = parent_path.get_indices() parent_path_list = parent_path.get_indices()
for i in range(len(parent_path_list)): for i in enumerate(parent_path_list):
expand_path = Gtk.TreePath( expand_path = Gtk.TreePath(
tuple([x for x in parent_path_list[:i+1]])) tuple([x for x in parent_path_list[:i+1]]))
self.list.expand_row(expand_path, False) self.list.expand_row(expand_path, False)

View File

@ -412,8 +412,8 @@ class FlatNodeMap:
""" """
#remove it from the full list first #remove it from the full list first
if not self._identical: if not self._identical:
for indx in range(len(self._fullhndl)): for indx, hndle in enumerate(self._fullhndl):
if self._fullhndl[indx][1] == handle: if self.hndle[1] == handle:
del self._fullhndl[indx] del self._fullhndl[indx]
break break
#now remove it from the index maps #now remove it from the index maps

View File

@ -711,7 +711,7 @@ class TreeBaseModel(GObject.GObject, Gtk.TreeModel, BaseModel):
does not update for every change signal. does not update for every change signal.
""" """
if node.children: if node.children:
rows = list(range(len(node.children)-1,-1,-1)) rows = reversed(node.children)
if node.parent is None: if node.parent is None:
path = iter = None path = iter = None
else: else:

View File

@ -422,7 +422,7 @@ class FanChartBaseWidget(Gtk.DrawingArea):
divs = [x/(steps-1) for x in range(steps)] divs = [x/(steps-1) for x in range(steps)]
self.gradval = ['%d' % int(x * MAX_AGE) for x in divs] self.gradval = ['%d' % int(x * MAX_AGE) for x in divs]
self.gradval[-1] = '%d+' % MAX_AGE self.gradval[-1] = '%d+' % MAX_AGE
for i in range(len(self.gradval)): for i in enumerate(self.gradval):
if i % 2 == 1: if i % 2 == 1:
self.gradval[i] = '' self.gradval[i] = ''
self.gradcol = [colorsys.hsv_to_rgb( self.gradcol = [colorsys.hsv_to_rgb(
@ -1310,7 +1310,7 @@ class FanChartWidget(FanChartBaseWidget):
angle = self.rootangle_rad[0] angle = self.rootangle_rad[0]
portion = 1/ (2 ** i) * (self.rootangle_rad[1] - portion = 1/ (2 ** i) * (self.rootangle_rad[1] -
self.rootangle_rad[0]) self.rootangle_rad[0])
for dummy_count in range(len(self.data[i])): for dummy_count in self.data[i]:
# start, stop, state # start, stop, state
self.angle[i].append([angle, angle + portion, NORMAL]) self.angle[i].append([angle, angle + portion, NORMAL])
angle += portion angle += portion
@ -1397,9 +1397,7 @@ class FanChartWidget(FanChartBaseWidget):
""" """
#compute the number of generations present #compute the number of generations present
for generation in range(self.generations - 1, 0, -1): for generation in range(self.generations - 1, 0, -1):
for idx in range(len(self.data[generation])): for (person, *rest) in self.data[generation]:
(person, dummy_parents, dummy_child,
dummy_userdata) = self.data[generation][idx]
if person: if person:
return generation return generation
return 1 return 1
@ -1423,10 +1421,8 @@ class FanChartWidget(FanChartBaseWidget):
a generator over all people outside of the core person a generator over all people outside of the core person
""" """
for generation in range(self.generations): for generation in range(self.generations):
for idx in range(len(self.data[generation])): for (person, dummy_parents, dummy_child, userdata) in self.data[generation]:
(person, dummy_parents, dummy_child, yield person, userdata
userdata) = self.data[generation][idx]
yield (person, userdata)
def innerpeople_generator(self): def innerpeople_generator(self):
""" """
@ -1477,13 +1473,11 @@ class FanChartWidget(FanChartBaseWidget):
ctx.save() ctx.save()
ctx.rotate(math.radians(self.rotate_value)) ctx.rotate(math.radians(self.rotate_value))
for generation in range(self.generations - 1, 0, -1): for generation in range(self.generations - 1, 0, -1):
for idx in range(len(self.data[generation])): for idx, (person, parents, child, userdata) in enumerate(self.data[generation]):
(person, parents, child, userdata) = self.data[generation][idx]
if person: if person:
start, stop, state = self.angle[generation][idx] start, stop, state = self.angle[generation][idx]
if state in [NORMAL, EXPANDED]: if state in [NORMAL, EXPANDED]:
(radiusin, (radiusin, radiusout) = self.get_radiusinout_for_gen(generation)
radiusout) = self.get_radiusinout_for_gen(generation)
dup = False dup = False
indicator = (generation == self.generations - 1 indicator = (generation == self.generations - 1
and parents) and parents)
@ -1689,8 +1683,7 @@ class FanChartWidget(FanChartBaseWidget):
if not (generation is None) and generation > 0: if not (generation is None) and generation > 0:
selected = self.personpos_at_angle(generation, rads) selected = self.personpos_at_angle(generation, rads)
elif generation == -2: elif generation == -2:
for idx in range(len(self.angle[generation])): for idx, (start, stop, dummy_state) in enumerate(self.angle[generation]):
start, stop, dummy_state = self.angle[generation][idx]
if self.radian_in_bounds(start, raw_rads, stop): if self.radian_in_bounds(start, raw_rads, stop):
selected = idx selected = idx
break break
@ -1705,9 +1698,8 @@ class FanChartWidget(FanChartBaseWidget):
if generation == 0: if generation == 0:
return 0 return 0
selected = None selected = None
for idx in range(len(self.angle[generation])): for idx, (start, stop, state) in enumerate(self.angle[generation]):
if self.data[generation][idx][0]: # there is a person there if self.data[generation][idx][0]: # there is a person there
start, stop, state = self.angle[generation][idx]
if state == COLLAPSED: if state == COLLAPSED:
continue continue
if self.radian_in_bounds(start, rads, stop): if self.radian_in_bounds(start, rads, stop):

View File

@ -195,7 +195,7 @@ class FanChart2WayWidget(FanChartWidget, FanChartDescWidget):
angle = self.rootangle_rad_asc[0] angle = self.rootangle_rad_asc[0]
portion = 1 / (2 ** i) * (self.rootangle_rad_asc[1] - portion = 1 / (2 ** i) * (self.rootangle_rad_asc[1] -
self.rootangle_rad_asc[0]) self.rootangle_rad_asc[0])
for dummy_count in range(len(self.data[i])): for dummy_count in self.data[i]:
# start, stop, state # start, stop, state
self.angle[i].append([angle, angle + portion, NORMAL]) self.angle[i].append([angle, angle + portion, NORMAL])
angle += portion angle += portion
@ -259,9 +259,7 @@ class FanChart2WayWidget(FanChartWidget, FanChartDescWidget):
compute the number of generations present compute the number of generations present
""" """
for generation in range(self.generations_asc - 1, 0, -1): for generation in range(self.generations_asc - 1, 0, -1):
for idx in range(len(self.data[generation])): for idx, (person, *rest) in enumerate(self.data[generation]):
(person, dummy_parents, dummy_child,
dummy_userdata) = self.data[generation][idx]
if person: if person:
return generation return generation
return 1 return 1
@ -349,10 +347,8 @@ class FanChart2WayWidget(FanChartWidget, FanChartDescWidget):
for data in self.gen2fam[generation]: for data in self.gen2fam[generation]:
yield (data[7], data[6]) yield (data[7], data[6])
for generation in range(self.generations_asc): for generation in range(self.generations_asc):
for idx in range(len(self.data[generation])): for (person, dummy_parents, dummy_child, userdata) in self.data[generation]:
(person, dummy_parents, dummy_child, yield person, userdata
userdata) = self.data[generation][idx]
yield (person, userdata)
def innerpeople_generator(self): def innerpeople_generator(self):
""" """
@ -458,9 +454,7 @@ class FanChart2WayWidget(FanChartWidget, FanChartDescWidget):
ctx.rotate(math.radians(self.rotate_value)) ctx.rotate(math.radians(self.rotate_value))
# Ascendance # Ascendance
for generation in range(self.generations_asc - 1, 0, -1): for generation in range(self.generations_asc - 1, 0, -1):
for idx in range(len(self.data[generation])): for idx, (person, parents, dummy_child, userdata) in enumerate(self.data[generation]):
(person, parents, dummy_child,
userdata) = self.data[generation][idx]
if person: if person:
start, stop, state = self.angle[generation][idx] start, stop, state = self.angle[generation][idx]
if state in [NORMAL, EXPANDED]: if state in [NORMAL, EXPANDED]:

View File

@ -555,8 +555,7 @@ class FanChartDescWidget(FanChartBaseWidget):
if not (generation is None) and generation > 0: if not (generation is None) and generation > 0:
selected = self.personpos_at_angle(generation, rads, btype) selected = self.personpos_at_angle(generation, rads, btype)
elif generation == -2: elif generation == -2:
for idx in range(len(self.angle[generation])): for idx, (start, stop, dummy) in enumerate(self.angle[generation]):
start, stop, dummy_state = self.angle[generation][idx]
if self.radian_in_bounds(start, raw_rads, stop): if self.radian_in_bounds(start, raw_rads, stop):
selected = idx selected = idx
break break

View File

@ -1309,7 +1309,7 @@ class GrampletPane(Gtk.ScrolledWindow):
x = sx - x x = sx - x
# first, find column: # first, find column:
col = 0 col = 0
for i in range(len(self.columns)): for i in enumerate(self.columns):
if x < (sx/len(self.columns) * (i + 1)): if x < (sx/len(self.columns) * (i + 1)):
col = i col = i
break break

View File

@ -114,7 +114,7 @@ class ShortlistComboEntry(ValidatedComboEntry):
# remove the existing shortlist from the model # remove the existing shortlist from the model
iter = model.get_iter_first() iter = model.get_iter_first()
for n in range(len(self._shortlist)): for n in self._shortlist:
model.remove(iter) model.remove(iter)
# update shortlist # update shortlist

View File

@ -184,7 +184,7 @@ class CairoDocgen(libcairodoc.CairoDoc):
body_pages = body_pages[:index_page] + index_pages + \ body_pages = body_pages[:index_page] + index_pages + \
body_pages[index_page+1:] body_pages[index_page+1:]
self._pages = body_pages self._pages = body_pages
for page_nr in range(len(self._pages)): for page_nr in enumerate(self._pages):
cr.save() cr.save()
cr.translate(left_margin, top_margin) cr.translate(left_margin, top_margin)
self.draw_page(page_nr, cr, layout, self.draw_page(page_nr, cr, layout,

View File

@ -475,7 +475,7 @@ def str_incr(str_counter):
raise ValueError(''.join(( raise ValueError(''.join((
'\n can\'t increment string ', ''.join(lili), '\n can\'t increment string ', ''.join(lili),
' of length ', str(len(lili))))) ' of length ', str(len(lili)))))
for i in range(len(lili)-1, -1, -1): for i in reversed(lili):
if lili[i] < 'z': if lili[i] < 'z':
lili[i] = chr(ord(lili[i])+1) lili[i] = chr(ord(lili[i])+1)
break break

View File

@ -1066,8 +1066,8 @@ class MakeReport:
def __reverse_family_group(self): def __reverse_family_group(self):
""" go through the n-1 to 0 cols of boxes looking for families """ go through the n-1 to 0 cols of boxes looking for families
(parents with children) that may need to be moved. """ (parents with children) that may need to be moved. """
for x_col in range(len(self.cols)-1, -1, -1): for col in reversed(self.cols):
box = self.cols[x_col][0] #The first person in this col box = col[0] #The first person in this col
while box: while box:
left_group, right_group = self.__next_family_group(box) left_group, right_group = self.__next_family_group(box)
if not left_group: if not left_group:

View File

@ -1022,8 +1022,7 @@ class StatisticsChartOptions(MenuReportOptions):
sortby = EnumeratedListOption(_('Sort chart items by'), sortby = EnumeratedListOption(_('Sort chart items by'),
_options.SORT_VALUE) _options.SORT_VALUE)
for item_idx in range(len(_options.opt_sorts)): for item_idx, item in enumerate(_options.opt_sorts):
item = _options.opt_sorts[item_idx]
sortby.add_item(item_idx, item[2]) sortby.add_item(item_idx, item[2])
sortby.set_help(_("Select how the statistical data is sorted.")) sortby.set_help(_("Select how the statistical data is sorted."))
add_option("sortby", sortby) add_option("sortby", sortby)
@ -1051,8 +1050,7 @@ class StatisticsChartOptions(MenuReportOptions):
gender = EnumeratedListOption(_('Genders included'), gender = EnumeratedListOption(_('Genders included'),
Person.UNKNOWN) Person.UNKNOWN)
for item_idx in range(len(_options.opt_genders)): for item in enumerate(_options.opt_genders):
item = _options.opt_genders[item_idx]
gender.add_item(item[0], item[2]) gender.add_item(item[0], item[2])
gender.set_help(_("Select which genders are included into " gender.set_help(_("Select which genders are included into "
"statistics.")) "statistics."))

View File

@ -144,8 +144,8 @@ class Leak(Gramplet):
try: try:
if referrer is not self.junk: if referrer is not self.junk:
match = "**** " match = "**** "
for indx in range(len(self.junk)): for indx, junk in enumerate(self.junk):
if referrer is self.junk[indx]: if referrer is junk:
match = str(indx) + ": " match = str(indx) + ": "
break break
match += str(referrer) + '\n' match += str(referrer) + '\n'
@ -167,8 +167,8 @@ class Leak(Gramplet):
match = "" match = ""
try: try:
match = "****: " match = "****: "
for indx in range(len(self.junk)): for indx, junk in enumerate(self.junk):
if referent is self.junk[indx]: if referent is junk:
match = str(indx) + ': ' match = str(indx) + ': '
break break
match += str(referent) + '\n' match += str(referent) + '\n'

View File

@ -149,8 +149,8 @@ class FamilyLinesOptions(MenuReportOptions):
add_option("arrow", arrow) add_option("arrow", arrow)
color = EnumeratedListOption(_("Graph coloring"), "filled") color = EnumeratedListOption(_("Graph coloring"), "filled")
for i in range(len(_COLORS)): for COLOR in _COLORS:
color.add_item(_COLORS[i]["value"], _COLORS[i]["name"]) color.add_item(COLOR["value"], COLOR["name"])
color.set_help(_("Males will be shown with blue, females " color.set_help(_("Males will be shown with blue, females "
"with red, unless otherwise set above for filled. " "with red, unless otherwise set above for filled. "
"If the sex of an individual " "If the sex of an individual "

View File

@ -170,8 +170,8 @@ def tabstops_to_tabarray(tab_stops, dpi):
tab_array = Pango.TabArray.new(initial_size=len(tab_stops), tab_array = Pango.TabArray.new(initial_size=len(tab_stops),
positions_in_pixels=False) positions_in_pixels=False)
for index in range(len(tab_stops)): for index, tab_stop in enumerate(tab_stops):
location = tab_stops[index] * dpi * Pango.SCALE / 2.54 location = tab_stop * dpi * Pango.SCALE / 2.54
tab_array.set_tab(index, Pango.TabAlign.LEFT, int(location)) tab_array.set_tab(index, Pango.TabAlign.LEFT, int(location))
return tab_array return tab_array

View File

@ -380,17 +380,17 @@ class PG30DefTable(object):
""" Convert records to list. """ """ Convert records to list. """
flds = [] flds = []
for i in range(len(rec)): for i, record in enumerate(rec):
typ = self.recflds[i].type_ typ = self.recflds[i].type_
if typ == 2 or typ == 3 or typ == 22 or typ == 23: if typ == 2 or typ == 3 or typ == 22 or typ == 23:
# Record field is record number # Record field is record number
flds.append("%d" % rec[i]) flds.append("%d" % record)
elif typ == 46 or typ == 47: elif typ == 46 or typ == 47:
# Record field is memory type # Record field is memory type
flds.append(self.get_mem_text(mems, rec[i])) flds.append(self.get_mem_text(mems, rec[i]))
else: else:
# Not a record number, not a memory type. It must be just text. # Not a record number, not a memory type. It must be just text.
fld = rec[i].strip() fld = record.strip()
fld = fld.decode('cp850') # Convert to unicode fld = fld.decode('cp850') # Convert to unicode
flds.append(fld) flds.append(fld)

View File

@ -114,8 +114,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator):
def get_direct_ancestor(self, person, rel_string): def get_direct_ancestor(self, person, rel_string):
result = [] result = []
for ix in range(len(rel_string)): for rel in rel_string:
if rel_string[ix] == 'f': if rel == 'f':
result.append('far') result.append('far')
else: else:
result.append('mor') result.append('mor')

View File

@ -102,8 +102,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator):
def get_direct_ancestor(self, person, rel_string): def get_direct_ancestor(self, person, rel_string):
result = [] result = []
for ix in range(len(rel_string)): for rel in rel_string:
if rel_string[ix] == 'f': if rel == 'f':
result.append('faðir') result.append('faðir')
else: else:
result.append('móðir') result.append('móðir')

View File

@ -101,8 +101,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator):
def get_direct_ancestor(self, person, rel_string): def get_direct_ancestor(self, person, rel_string):
result = [] result = []
for ix in range(len(rel_string)): for rel in rel_string:
if rel_string[ix] == 'f': if rel == 'f':
result.append('far') result.append('far')
else: else:
result.append('mor') result.append('mor')

View File

@ -124,8 +124,8 @@ class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator):
def _get_direct_ancestor(self, person_gender, rel_string, step, inlaw): def _get_direct_ancestor(self, person_gender, rel_string, step, inlaw):
result = [] result = []
for ix in range(len(rel_string)): for rel in rel_string:
if rel_string[ix] == 'f': if rel == 'f':
result.append('far') result.append('far')
else: else:
result.append('mor') result.append('mor')

View File

@ -120,15 +120,15 @@ class CategorySidebar(BaseSidebar):
""" """
Block signals to the buttons to prevent spurious events. Block signals to the buttons to prevent spurious events.
""" """
for idx in range(len(self.buttons)): for idx, button in enumerate(self.buttons):
self.buttons[idx].handler_block(self.button_handlers[idx]) button.handler_block(self.button_handlers[idx])
def __handlers_unblock(self): def __handlers_unblock(self):
""" """
Unblock signals to the buttons. Unblock signals to the buttons.
""" """
for idx in range(len(self.buttons)): for idx, button in enumerate(self.buttons):
self.buttons[idx].handler_unblock(self.button_handlers[idx]) button.handler_unblock(self.button_handlers[idx])
def cb_view_clicked(self, radioaction, current, cat_num): def cb_view_clicked(self, radioaction, current, cat_num):
""" """

View File

@ -92,15 +92,15 @@ class DropdownSidebar(BaseSidebar):
""" """
Block signals to the buttons to prevent spurious events. Block signals to the buttons to prevent spurious events.
""" """
for idx in range(len(self.buttons)): for idx, button in enumerate(self.buttons):
self.buttons[idx].handler_block(self.button_handlers[idx]) button.handler_block(self.button_handlers[idx])
def __handlers_unblock(self): def __handlers_unblock(self):
""" """
Unblock signals to the buttons. Unblock signals to the buttons.
""" """
for idx in range(len(self.buttons)): for idx, button in enumerate(self.buttons):
self.buttons[idx].handler_unblock(self.button_handlers[idx]) button.handler_unblock(self.button_handlers[idx])
def cb_view_clicked(self, radioaction, current, cat_num): def cb_view_clicked(self, radioaction, current, cat_num):
""" """

View File

@ -124,15 +124,15 @@ class ExpanderSidebar(BaseSidebar):
""" """
Block signals to the buttons to prevent spurious events. Block signals to the buttons to prevent spurious events.
""" """
for idx in range(len(self.buttons)): for idx, button in enumerate(self.buttons):
self.buttons[idx].handler_block(self.button_handlers[idx]) button.handler_block(self.button_handlers[idx])
def __handlers_unblock(self): def __handlers_unblock(self):
""" """
Unblock signals to the buttons. Unblock signals to the buttons.
""" """
for idx in range(len(self.buttons)): for idx, button in enumerate(self.buttons):
self.buttons[idx].handler_unblock(self.button_handlers[idx]) button.handler_unblock(self.button_handlers[idx])
def cb_view_clicked(self, radioaction, current, cat_num): def cb_view_clicked(self, radioaction, current, cat_num):
""" """

View File

@ -309,8 +309,8 @@ class DetDescendantReport(Report):
""" Entry Filter for Record-style (Modified Register) numbering """ """ Entry Filter for Record-style (Modified Register) numbering """
self.apply_mod_reg_filter_aux(person_handle, 1, 1) self.apply_mod_reg_filter_aux(person_handle, 1, 1)
mod_reg_number = 1 mod_reg_number = 1
for generation in range(len(self.gen_keys)): for keys in self.gen_keys:
for key in self.gen_keys[generation]: for key in keys:
person_handle = self.map[key] person_handle = self.map[key]
if person_handle not in self.dnumber: if person_handle not in self.dnumber:
self.dnumber[person_handle] = mod_reg_number self.dnumber[person_handle] = mod_reg_number
@ -348,7 +348,7 @@ class DetDescendantReport(Report):
self.numbers_printed = list() self.numbers_printed = list()
if self.structure == "by generation": if self.structure == "by generation":
for generation in range(len(self.gen_keys)): for generation, gen_keys in enumerate(self.gen_keys):
if self.pgbrk and generation > 0: if self.pgbrk and generation > 0:
self.doc.page_break() self.doc.page_break()
self.doc.start_paragraph("DDR-Generation") self.doc.start_paragraph("DDR-Generation")
@ -359,7 +359,7 @@ class DetDescendantReport(Report):
if self.childref: if self.childref:
self.prev_gen_handles = self.gen_handles.copy() self.prev_gen_handles = self.gen_handles.copy()
self.gen_handles.clear() self.gen_handles.clear()
for key in self.gen_keys[generation]: for key in gen_keys:
person_handle = self.map[key] person_handle = self.map[key]
self.gen_handles[person_handle] = key self.gen_handles[person_handle] = key
self.write_person(key) self.write_person(key)