Commit 238c72d0 authored by Michael Büsch's avatar Michael Büsch

compat: Add dict items() values() keys() compat

Signed-off-by: Michael Büsch's avatarMichael Buesch <m@bues.ch>
parent 3a63ec29
......@@ -90,7 +90,7 @@ def usage():
print(" --list-sfb-verbose Verbose SFB list")
def printSysblockInfo(blockTable, prefix, withExtended, withInterface):
for block in sorted(blockTable.values(),
for block in sorted(dictValues(blockTable),
key = lambda b: b.name[0]):
if block.broken:
continue
......
......@@ -182,3 +182,12 @@ if not hasattr(contextlib, "suppress"):
def __exit__(self, exctype, excinst, exctb):
return exctype is not None and issubclass(exctype, self._excs)
contextlib.suppress = _suppress
# Dict items(), keys(), values() compatibility.
# Use Python3 behavior.
dictItems = py23(lambda d: d.viewitems(),
lambda d: d.items())
dictKeys = py23(lambda d: d.viewkeys(),
lambda d: d.keys())
dictValues = py23(lambda d: d.viewvalues(),
lambda d: d.values())
......@@ -66,7 +66,7 @@ class HwmodDescriptor(object):
if not parameters:
parameters = {}
self.parameters = {}
for name, value in parameters.items():
for name, value in dictItems(parameters):
self.addParameter(name, value)
self.__identHash = None
......@@ -105,7 +105,7 @@ class HwmodDescriptor(object):
# Calculate the ident hash
h = self.IDENT_HASH(b"HwmodDescriptor")
h.update(self.moduleName.encode("utf-8", "ignore"))
for pName, pValue in sorted(self.parameters.items(),
for pName, pValue in sorted(dictItems(self.parameters),
key = lambda item: item[0]):
h.update(pName.encode("utf-8", "ignore"))
h.update(pValue.encode("utf-8", "ignore"))
......
......@@ -751,7 +751,7 @@ class Project(object):
modName = strToBase64(modDesc.getModuleName(),
ignoreErrors=True)
lines.append("loaded_mod_%d=%s" % (modNr, modName))
modParams = sorted(list(modDesc.getParameters().items()),
modParams = sorted(dictItems(modDesc.getParameters()),
key = lambda p: p[0])
for paramNr, param in enumerate(modParams):
paramName, paramValue = param
......
......@@ -257,10 +257,13 @@ def isiterable(obj):
pass
return False
def getany(iterable, exception=KeyError):
"""Get an arbitrary item from an iterable.
def getfirst(iterable, exception=KeyError):
"""Get the first item from an iterable.
This also works for generators.
If the iterable is empty, exception is raised.
If exception is None, None is returned instead.
Warning: If iterable is not indexable (for example a set),
an arbitrary item is returned instead.
"""
try:
return next(iter(iterable))
......@@ -269,6 +272,11 @@ def getany(iterable, exception=KeyError):
raise exception
return None
# Get an arbitrary item from an iterable.
# If the iterable is empty, exception is raised.
# If exception is None, None is returned instead.
getany = getfirst
def toList(value):
"""Returns value, if value is a list.
Returns a list with the elements of value, if value is a set.
......
......@@ -336,7 +336,7 @@ class S7Prog(object):
self.pendingRawUDTs = []
# Build all UDTs (Resolve sizes of all fields)
for udt in udts.values():
for udt in dictValues(udts):
udt.buildDataStructure(self.cpu)
# Translate OBs
......@@ -409,7 +409,7 @@ class S7Prog(object):
if not self.cpu.sfbs:
# Create the SFB tables
for sfbNumber in SFB_table.keys():
for sfbNumber in dictKeys(SFB_table):
if sfbNumber < 0 and not self.cpu.extendedInsnsEnabled():
continue
sfb = SFB_table[sfbNumber](self.cpu)
......@@ -417,7 +417,7 @@ class S7Prog(object):
if not self.cpu.sfcs:
# Create the SFC tables
for sfcNumber in SFC_table.keys():
for sfcNumber in dictKeys(SFC_table):
if sfcNumber < 0 and not self.cpu.extendedInsnsEnabled():
continue
sfc = SFC_table[sfcNumber](self.cpu)
......@@ -460,13 +460,13 @@ class S7Prog(object):
blkInfos = []
for block in itertools.chain(
sorted(self.cpu.obs.values() if getOBInfo else [],
sorted(dictValues(self.cpu.obs) if getOBInfo else [],
key = lambda blk: blk.index),
sorted(self.cpu.fcs.values() if getFCInfo else [],
sorted(dictValues(self.cpu.fcs) if getFCInfo else [],
key = lambda blk: blk.index),
sorted(self.cpu.fbs.values() if getFBInfo else [],
sorted(dictValues(self.cpu.fbs) if getFBInfo else [],
key = lambda blk: blk.index),
sorted(self.cpu.dbs.values() if getDBInfo else [],
sorted(dictValues(self.cpu.dbs) if getDBInfo else [],
key = lambda blk: blk.index)):
blkInfo = block.getBlockInfo()
assert(blkInfo)
......@@ -547,25 +547,21 @@ class S7CPU(object): #+cdef
# Returns all user defined code blocks (OBs, FBs, FCs)
def allUserCodeBlocks(self):
for ob in self.obs.values():
yield ob
for fb in self.fbs.values():
yield fb
for fc in self.fcs.values():
yield fc
for block in itertools.chain(dictValues(self.obs),
dictValues(self.fbs),
dictValues(self.fcs)):
yield block
# Returns all system code blocks (SFBs, SFCs)
def allSystemCodeBlocks(self):
for sfb in self.sfbs.values():
yield sfb
for sfc in self.sfcs.values():
yield sfc
for block in itertools.chain(dictValues(self.sfbs),
dictValues(self.sfcs)):
yield block
# Returns all user defined code blocks (OBs, FBs, FCs, SFBs, SFCs)
def allCodeBlocks(self):
for block in self.allUserCodeBlocks():
yield block
for block in self.allSystemCodeBlocks():
for block in itertools.chain(self.allUserCodeBlocks(),
self.allSystemCodeBlocks()):
yield block
def allCallInsns(self, block):
......@@ -648,19 +644,19 @@ class S7CPU(object): #+cdef
self.prog.build()
def load(self, parseTree, rebuild = False, sourceManager = None):
for rawDB in parseTree.dbs.values():
for rawDB in dictValues(parseTree.dbs):
rawDB.setSourceRef(sourceManager)
self.prog.addRawDB(rawDB)
for rawFB in parseTree.fbs.values():
for rawFB in dictValues(parseTree.fbs):
rawFB.setSourceRef(sourceManager)
self.prog.addRawFB(rawFB)
for rawFC in parseTree.fcs.values():
for rawFC in dictValues(parseTree.fcs):
rawFC.setSourceRef(sourceManager)
self.prog.addRawFC(rawFC)
for rawOB in parseTree.obs.values():
for rawOB in dictValues(parseTree.obs):
rawOB.setSourceRef(sourceManager)
self.prog.addRawOB(rawOB)
for rawUDT in parseTree.udts.values():
for rawUDT in dictValues(parseTree.udts):
rawUDT.setSourceRef(sourceManager)
self.prog.addRawUDT(rawUDT)
if rebuild:
......@@ -717,9 +713,11 @@ class S7CPU(object): #+cdef
def reset(self):
self.prog.reset()
for block in itertools.chain(self.udts.values(), self.dbs.values(),
self.obs.values(), self.fcs.values(),
self.fbs.values()):
for block in itertools.chain(dictValues(self.udts),
dictValues(self.dbs),
dictValues(self.obs),
dictValues(self.fcs),
dictValues(self.fbs)):
block.destroySourceRef()
self.udts = {} # UDTs
self.dbs = { # DBs
......
......@@ -274,7 +274,7 @@ class AbstractHardwareInterface(object):
# Parse the parameters.
self.__paramsByName = {}
self.__paramsByDescType = {}
for name, value in parameters.items():
for name, value in dictItems(parameters):
for desc in self.getParamDescs():
if desc.match(name):
break
......@@ -295,7 +295,7 @@ class AbstractHardwareInterface(object):
for desc in self.getParamDescs():
if not desc.mandatory:
continue
if desc.name not in self.__paramsByName.keys():
if desc.name not in dictKeys(self.__paramsByName):
self.paramErrorHandler(desc.name,
"Mandatory parameter not specified")
......
......@@ -420,7 +420,7 @@ class AwlInsn(object): #+cdef
# Create a name2type dict for english mnemonics using the translation dict.
name2type_english = {}
for _name, _insnType in name2type_german.items():
for _name, _insnType in dictItems(name2type_german):
with contextlib.suppress(KeyError):
_name = german2english[_name]
name2type_english[_name] = _insnType
......@@ -521,4 +521,4 @@ class AwlInsn(object): #+cdef
# Sanity check of english2german table
assert(all(germanName in AwlInsn.name2type_german \
for englishName, germanName in AwlInsn.english2german.items()))
for englishName, germanName in dictItems(AwlInsn.english2german)))
......@@ -219,7 +219,7 @@ class AwlOpTranslator(object):
# Create a constOperTab for english mnemonics
__constOperTab_english = {}
for name, type in __constOperTab_german.items():
for name, type in dictItems(__constOperTab_german):
try:
name = __german2english[name]
except KeyError:
......@@ -596,7 +596,7 @@ class AwlOpTranslator(object):
# For example:
# = M0.0
# (Note the missing white space between M and 0.0)
for name, opDesc in operTable.items():
for name, opDesc in dictItems(operTable):
if isinstance(opDesc.operator.value, AwlOffset) and\
opDesc.operator.value.byteOffset >= 0 and\
opDesc.operator.value.bitOffset >= 0:
......
......@@ -84,10 +84,10 @@ class AwlTranslator(object):
tree = p.getParseTree()
if block.isFC:
assert(len(tree.fcs) == 1)
rawBlock = tuple(tree.fcs.values())[0]
rawBlock = getfirst(dictValues(tree.fcs))
elif block.isFB:
assert(len(tree.fbs) == 1)
rawBlock = tuple(tree.fbs.values())[0]
rawBlock = getfirst(dictValues(tree.fbs))
else:
assert(0)
# Translate the library block instructions.
......
......@@ -91,7 +91,7 @@ def toSet(value):
def pivotDict(inDict):
outDict = {}
for key, value in inDict.items():
for key, value in dictItems(inDict):
if value in outDict:
raise KeyError("Ambiguous key in pivot dict")
outDict[value] = key
......
......@@ -388,7 +388,7 @@ class AwlSimMessage_HWMOD(AwlSimMessage):
payload = b""
try:
payload += self.packString(self.hwmodDesc.getModuleName())
for pname, pval in self.hwmodDesc.getParameters().items():
for pname, pval in dictItems(self.hwmodDesc.getParameters()):
payload += self.packString(pname)
payload += self.packString(pval)
return AwlSimMessage.toBytes(self, len(payload)) + payload
......@@ -948,7 +948,7 @@ class AwlSimMessage_IDENTS(AwlSimMessage):
params = hwmodDesc.getParameters()
payload.append(self.plModStruct.pack(len(params), 0))
payload.append(self.packString(hwmodDesc.getModuleName()))
for pName, pVal in params.items():
for pName, pVal in dictItems(params):
payload.append(self.packString(pName))
payload.append(self.packString(pVal))
for libSel in self.libSelections:
......
......@@ -212,7 +212,7 @@ class BitDisplayWidget(AbstractDisplayWidget):
y += 1
def __buttonUpdate(self):
for bitNr, pb in self.pbs.items():
for bitNr, pb in dictItems(self.pbs):
pressed = bool(pb.isDown())
if pressed == self.prevButtonStates[bitNr]:
continue
......@@ -225,7 +225,7 @@ class BitDisplayWidget(AbstractDisplayWidget):
def get(self):
value = 0
for bitNr, cb in self.cbs.items():
for bitNr, cb in dictItems(self.cbs):
if cb.checkState() == Qt.Checked:
value |= (1 << bitNr)
return value
......
......@@ -581,7 +581,7 @@ class EditWidget(SourceCodeEdit):
# First instruction in cycle?
if insnDumpMsg.serial == 0:
# Update the 'obsolete'-flag based on the timestamp
for ent in self.__lineCpuStats.values():
for ent in dictValues(self.__lineCpuStats):
ent.obsolete = (ent.stamp != self.__cpuStatsStamp)
# Advance the timestamp
self.__cpuStatsStamp += 1
......@@ -590,7 +590,7 @@ class EditWidget(SourceCodeEdit):
if self.__runState.state == RunState.STATE_OFFLINE:
return
firstLine, lastLine = self.getVisibleLineRange()
for line, stats in self.__lineCpuStats.items():
for line, stats in dictItems(self.__lineCpuStats):
if line < firstLine or line > lastLine:
stats.pruned = True
stats.obsolete = True
......
......@@ -41,7 +41,7 @@ class HwmodParamModel(QAbstractTableModel):
"""Return a list of tuples: (paramName, paramValue)"""
if not self.modDesc:
return []
return sorted(list(self.modDesc.getParameters().items()),
return sorted(dictItems(self.modDesc.getParameters()),
key = lambda p: p[0])
def __getParamDesc(self, paramName):
......
......@@ -346,7 +346,7 @@ class LibraryDialog(QDialog):
def __addSystemBlockTable(self, prefix, table):
entries = []
for blockCls in sorted(table.values(), key=lambda c: c.name[0]):
for blockCls in sorted(dictValues(table), key=lambda c: c.name[0]):
if blockCls.broken:
continue
number, name, desc = blockCls.name
......
......@@ -164,7 +164,7 @@ class AwlLibEntry(StaticCodeBlock):
def _generateInterfaceCode(self, special_RET_VAL=False):
code = []
retValType = None
for ftype, fields in sorted(self.interfaceFields.items(),
for ftype, fields in sorted(dictItems(self.interfaceFields),
key=lambda i: i[0]):
decl = {
BlockInterfaceField.FTYPE_IN : "VAR_INPUT",
......
......@@ -161,11 +161,11 @@ class RpiGPIO_HwInterface(AbstractHardwareInterface):
except RuntimeError as e:
self.raiseException("Failed to init Raspberry Pi "
"BCM%d: %s" % (bcmNumber, str(e)))
for bitMapping in mapDict.values():
for bitMapping in dictValues(mapDict):
bitMapping.build()
mapList = list(sorted(
[ (byteOffset, bitMapping)
for byteOffset, bitMapping in mapDict.items() ],
for byteOffset, bitMapping in dictItems(mapDict) ],
key = lambda _tuple: _tuple[0]
))
return mapDict, mapList
......
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