Commit 358c3016 authored by Nicolas Chauvat's avatar Nicolas Chauvat
Browse files

[toward py3k] rewrite dict.keys() and dict.values() (part of #2711624)

Python 3K will only expose iterators.

http://docs.python.org/3.0/whatsnew/3.0.html#views-and-iterators-instead-of-lists
parent 358d8bed9626
......@@ -215,7 +215,7 @@ def validation_error(entity, errors, substitutions=None, i18nvalues=None):
# set empty dict else translation won't be done for backward
# compatibility reason (see ValidationError.translate method)
substitutions = {}
for key in errors.keys():
for key in list(errors):
if isinstance(key, tuple):
errors[rname(*key)] = errors.pop(key)
return ValidationError(getattr(entity, 'eid', entity), errors,
......
......@@ -91,7 +91,7 @@ Examples:
# web/views/basecomponents.py
def registration_callback(vreg):
# register everything in the module except SeeAlsoComponent
vreg.register_all(globals().values(), __name__, (SeeAlsoVComponent,))
vreg.register_all(globals().itervalues(), __name__, (SeeAlsoVComponent,))
# conditionally register SeeAlsoVComponent
if 'see_also' in vreg.schema:
vreg.register(SeeAlsoVComponent)
......@@ -624,7 +624,7 @@ class CWRegistryStore(RegistryStore):
"""
self.schema = schema
for registry, regcontent in self.items():
for objects in regcontent.values():
for objects in regcontent.itervalues():
for obj in objects:
obj.schema = schema
......@@ -725,7 +725,7 @@ class CWRegistryStore(RegistryStore):
self.unregister(obj)
super(CWRegistryStore, self).initialization_completed()
if 'uicfg' in self: # 'uicfg' is not loaded in a pure repository mode
for rtags in self['uicfg'].values():
for rtags in self['uicfg'].itervalues():
for rtag in rtags:
# don't check rtags if we don't want to cleanup_interface_sobjects
rtag.init(self.schema, check=self.config.cleanup_interface_sobjects)
......
......@@ -393,7 +393,7 @@ def _execmany_thread(sql_connect, statements, dump_output_dir=None,
if isinstance(data[0], (tuple, list)):
columns = None
else:
columns = data[0].keys()
columns = list(data[0])
execmany_func(cu, statement, data, table, columns, encoding)
except Exception:
print 'unable to copy data into table %s', table
......@@ -755,7 +755,7 @@ class CWImportController(object):
self.tell(pformat(sorted(error[1])))
def _print_stats(self):
nberrors = sum(len(err) for err in self.errors.values())
nberrors = sum(len(err) for err in self.errors.itervalues())
self.tell('\nImport statistics: %i entities, %i types, %i relations and %i errors'
% (self.store.nb_inserted_entities,
self.store.nb_inserted_types,
......@@ -1056,7 +1056,7 @@ class SQLGenSourceWrapper(object):
# for a given inlined relation,
# browse each couple to be inserted
for data in datalist:
keys = data.keys()
keys = list(data)
# For inlined relations, it exists only two case:
# (rtype, cw_eid) or (cw_eid, rtype)
if keys[0] == 'cw_eid':
......
......@@ -251,7 +251,7 @@ def _iter_vreg_objids(vreg, done):
for reg, objdict in vreg.items():
if reg in ('boxes', 'contentnavigation'):
continue
for objects in objdict.values():
for objects in objdict.itervalues():
for obj in objects:
objid = '%s_%s' % (reg, obj.__regid__)
if objid in done:
......
......@@ -1206,7 +1206,7 @@ def not_selected(vreg, appobject):
# # XXX broken
# from cubicweb.devtools.apptest import TestEnvironment
# env = testclass._env = TestEnvironment('data', configcls=testclass.configcls)
# for reg in env.vreg.values():
# for reg in env.vreg.itervalues():
# reg._selected = {}
# try:
# orig_select_best = reg.__class__.__orig_select_best
......
......@@ -96,7 +96,7 @@ class WorkflowTC(CubicWebTC):
def setup_database(self):
req = self.request()
rschema = self.schema['in_state']
for rdef in rschema.rdefs.values():
for rdef in rschema.rdefs.itervalues():
self.assertEqual(rdef.cardinality, '1*')
self.member = self.create_user(req, 'member')
......
......@@ -553,7 +553,7 @@ class Entity(AppObject):
def __repr__(self):
return '<Entity %s %s %s at %s>' % (
self.e_schema, self.eid, self.cw_attr_cache.keys(), id(self))
self.e_schema, self.eid, list(self.cw_attr_cache), id(self))
def __cmp__(self, other):
raise NotImplementedError('comparison not implemented for %s' % self.__class__)
......
......@@ -219,7 +219,7 @@ class MemSchemaNotifyChanges(hook.SingleLastOperation):
repo.set_schema(repo.schema, rebuildinfered=rebuildinfered)
# CWUser class might have changed, update current session users
cwuser_cls = self.session.vreg['etypes'].etype_class('CWUser')
for session in repo._sessions.values():
for session in repo._sessions.itervalues():
session.user.__class__ = cwuser_cls
except Exception:
self.critical('error while setting schema', exc_info=True)
......
......@@ -26,7 +26,7 @@ from cubicweb.server import hook
def get_user_sessions(repo, ueid):
for session in repo._sessions.values():
for session in repo._sessions.itervalues():
if ueid == session.user.eid:
yield session
......
......@@ -46,7 +46,7 @@ else:
'%s relation should not be in support_relations' % rtype
return mapping
# for now, only pyrorql sources have a mapping
for source in repo.sources_by_uri.values():
for source in repo.sources_by_uri.itervalues():
if not isinstance(source, PyroRQLSource):
continue
sourceentity = session.entity_from_eid(source.eid)
......
......@@ -76,7 +76,7 @@ elif applcubicwebversion < (3, 6, 0) and cubicwebversion >= (3, 6, 0):
with hooks_control(session, session.HOOKS_ALLOW_ALL, 'integrity'):
for rschema in repo.schema.relations():
rpermsdict = permsdict.get(rschema.eid, {})
for rdef in rschema.rdefs.values():
for rdef in rschema.rdefs.itervalues():
for action in rdef.ACTIONS:
actperms = []
for something in rpermsdict.get(action == 'update' and 'add' or action, ()):
......
......@@ -74,7 +74,7 @@ for entity in rql('Any X WHERE X cw_source S, S eid %(s)s', {'s': source.eid}).e
# only cleanup entities table, remaining stuff should be cleaned by a c-c
# db-check to be run after this script
for entities in todelete.values():
for entities in todelete.itervalues():
system_source.delete_info_multi(session, entities, source_name)
......@@ -87,7 +87,7 @@ for mappart in rql('Any X,SCH WHERE X cw_schema SCH, X cw_for_source S, S eid %(
if schemaent.__regid__ != 'CWEType':
assert schemaent.__regid__ == 'CWRType'
sch = schema._eid_index[schemaent.eid]
for rdef in sch.rdefs.values():
for rdef in sch.rdefs.itervalues():
if not source.support_entity(rdef.subject) \
or not source.support_entity(rdef.object):
continue
......
......@@ -17,7 +17,7 @@ def turn_function_to_class(node):
def cubicweb_transform(module):
# handle objectify_predicate decorator (and its former name until bw compat
# is kept). Only look at module level functions, should be enough.
for assnodes in module.locals.values():
for assnodes in module.locals.itervalues():
for node in assnodes:
if isinstance(node, scoped_nodes.Function) and node.decorators:
for decorator in node.decorators.nodes:
......
......@@ -317,7 +317,7 @@ def check_mandatory_relations(schema, session, eids, fix=1):
continue
smandatory = set()
omandatory = set()
for rdef in rschema.rdefs.values():
for rdef in rschema.rdefs.itervalues():
if rdef.cardinality[0] in '1+':
smandatory.add(rdef.subject)
if rdef.cardinality[1] in '1+':
......@@ -345,7 +345,7 @@ def check_mandatory_attributes(schema, session, eids, fix=1):
for rschema in schema.relations():
if not rschema.final or rschema in VIRTUAL_RTYPES:
continue
for rdef in rschema.rdefs.values():
for rdef in rschema.rdefs.itervalues():
if rdef.cardinality[0] in '1+':
rql = 'Any X WHERE X %s NULL, X is %s, X cw_source S, S name "system"' % (
rschema, rdef.subject)
......
......@@ -457,7 +457,7 @@ class ServerMigrationHelper(MigrationHelper):
{'x': expreid}, ask_confirm=False)
else:
newexprs.pop(expression)
for expression in newexprs.values():
for expression in newexprs.itervalues():
expr = expression.expression
if not confirm or self.confirm('Add %s expression for %s permission of %s?'
% (expr, action, erschema)):
......
......@@ -1075,7 +1075,7 @@ class PartPlanInformation(object):
"""return all sources supporting given term / solindices"""
sources = [selected_source]
sourcesterms = self._sourcesterms
for source in sourcesterms.keys():
for source in list(sourcesterms):
if source is selected_source:
continue
if not (term in sourcesterms[source] and
......@@ -1099,9 +1099,9 @@ class PartPlanInformation(object):
# term has to belong to the same scope if there is more
# than the system source remaining
if len(sourcesterms) > 1 and not scope is self.rqlst:
candidates = (t for t in sourceterms.keys() if scope is ms_scope(t))
candidates = (t for t in sourceterms if scope is ms_scope(t))
else:
candidates = sourceterms #.iterkeys()
candidates = sourceterms
# we only want one unlinked term in each generated query
candidates = [t for t in candidates
if isinstance(t, (Constant, Relation)) or
......
......@@ -63,13 +63,13 @@ class ConnectionsSet(object):
# FIXME: what happends if a commit fail
# would need a two phases commit or like, but I don't know how to do
# this using the db-api...
for source, cnx in self.source_cnxs.values():
for source, cnx in self.source_cnxs.itervalues():
# let exception propagates
cnx.commit()
def rollback(self):
"""rollback the current transaction for this user"""
for source, cnx in self.source_cnxs.values():
for source, cnx in self.source_cnxs.itervalues():
# catch exceptions, rollback other sources anyway
try:
cnx.rollback()
......@@ -83,12 +83,12 @@ class ConnectionsSet(object):
"""close all connections in the set"""
if i_know_what_i_do is not True: # unexpected closing safety belt
raise RuntimeError('connections set shouldn\'t be closed')
for cu in self._cursors.values():
for cu in self._cursors.itervalues():
try:
cu.close()
except Exception:
continue
for _, cnx in self.source_cnxs.values():
for _, cnx in self.source_cnxs.itervalues():
try:
cnx.close()
except Exception:
......@@ -102,7 +102,7 @@ class ConnectionsSet(object):
def cnxset_freed(self):
"""connections set is being freed from a session"""
for source, cnx in self.source_cnxs.values():
for source, cnx in self.source_cnxs.itervalues():
source.cnxset_freed(cnx)
def sources(self):
......@@ -114,7 +114,7 @@ class ConnectionsSet(object):
if uri == 'system':
continue
yield source
#return [source_cnx[0] for source_cnx in self.source_cnxs.values()]
#return [source_cnx[0] for source_cnx in self.source_cnxs.itervalues()]
def source(self, uid):
"""return the source object with the given uri"""
......
......@@ -530,7 +530,7 @@ class InsertPlan(ExecutionPlan):
def relation_defs(self):
"""return the list for relation definitions to insert"""
for rdefs in self._expanded_r_defs.values():
for rdefs in self._expanded_r_defs.itervalues():
for rdef in rdefs:
yield rdef
for rdef in self.r_defs:
......
......@@ -123,7 +123,7 @@ def preprocess_inlined_relations(session, entity):
relations = []
activeintegrity = session.is_hook_category_activated('activeintegrity')
eschema = entity.e_schema
for attr in entity.cw_edited.iterkeys():
for attr in entity.cw_edited:
rschema = eschema.subjrels[attr]
if not rschema.final: # inlined relation
value = entity.cw_edited[attr]
......@@ -201,7 +201,7 @@ class Repository(object):
# changed. To any existing user object have a different class than
# the new loaded one. We are hot fixing this.
usercls = self.vreg['etypes'].etype_class('CWUser')
for session in self._sessions.values():
for session in self._sessions.itervalues():
if not isinstance(session.user, InternalManager):
session.user.__class__ = usercls
......@@ -327,7 +327,7 @@ class Repository(object):
self.querier.set_schema(schema)
# don't use self.sources, we may want to give schema even to disabled
# sources
for source in self.sources_by_uri.values():
for source in self.sources_by_uri.itervalues():
source.set_schema(schema)
self.schema = schema
......@@ -415,7 +415,7 @@ class Repository(object):
# XXX: session.cnxset is accessed from a local storage, would be interesting
# to see if there is a cnxset set in any thread specific data)
return '%s: %s (%s)' % (self._cnxsets_pool.qsize(),
','.join(session.user.login for session in self._sessions.values()
','.join(session.user.login for session in self._sessions.itervalues()
if session.cnxset),
threading.currentThread())
def shutdown(self):
......@@ -729,7 +729,7 @@ class Repository(object):
for rschema, _eschema in cwuser.attribute_definitions()
if not rschema.meta)
cwuserattrs = self._cwuser_attrs
for k in chain(fetch_attrs, query_attrs.iterkeys()):
for k in chain(fetch_attrs, query_attrs):
if k not in cwuserattrs:
raise Exception('bad input for find_user')
with self.internal_session() as session:
......@@ -738,7 +738,7 @@ class Repository(object):
rql = 'Any %s WHERE X is CWUser, ' % ','.join(var[1] for var in vars)
rql += ','.join('X %s %s' % (var[0], var[1]) for var in vars) + ','
rset = session.execute(rql + ','.join('X %s %%(%s)s' % (attr, attr)
for attr in query_attrs.iterkeys()),
for attr in query_attrs),
query_attrs)
return rset.rows
......@@ -962,7 +962,7 @@ class Repository(object):
def close_sessions(self):
"""close every opened sessions"""
for sessionid in self._sessions.keys():
for sessionid in self._sessions:
try:
self.close(sessionid, checkshuttingdown=False)
except Exception: # XXX BaseException?
......@@ -976,7 +976,7 @@ class Repository(object):
self.debug('cleaning session unused since %s',
strftime('%T', localtime(mintime)))
nbclosed = 0
for session in self._sessions.values():
for session in self._sessions.itervalues():
if session.timestamp < mintime:
self.close(session.id)
nbclosed += 1
......
......@@ -187,7 +187,7 @@ class AbstractSource(object):
except KeyError:
pass
# check for unknown options
if confdict and not confdict.keys() == ['adapter']:
if confdict and tuple(confdict) != ('adapter',):
if fail_if_unknown:
msg = _('unknown options %s') % ', '.join(confdict)
raise ValidationError(eid, {role_name('config', 'subject'): msg})
......@@ -242,7 +242,7 @@ class AbstractSource(object):
"""remove sensitive information such as login / password from source
definition
"""
for key in sourcedef.keys():
for key in list(sourcedef):
if not key in self.PUBLIC_KEYS:
sourcedef.pop(key)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment