Skip to content

Commit

Permalink
2-3-compatibilize python code
Browse files Browse the repository at this point in the history
  • Loading branch information
vvolkl committed Mar 24, 2020
1 parent 6019f0f commit 2e3b609
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 39 deletions.
9 changes: 7 additions & 2 deletions python/EventStore.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@


from __future__ import absolute_import, unicode_literals, print_function
from six.moves import range

from ROOT import gSystem
gSystem.Load("libpodioRootIO")
from ROOT import podio
Expand All @@ -6,7 +11,7 @@
def iterator(self):
'''dynamically added iterator'''
entries = self.size()
for entry in xrange(entries):
for entry in range(entries):
yield self.at(entry)


Expand Down Expand Up @@ -99,7 +104,7 @@ def __iter__(self):
'''
for nev, store in self.stores:
self.current_store = store
for entry in xrange(store.getEntries()):
for entry in range(store.getEntries()):
yield store
store.endOfEvent()

Expand Down
57 changes: 30 additions & 27 deletions python/podio_class_generator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
#!/usr/bin/env python
#!/usr/bin/env python

from __future__ import absolute_import, unicode_literals, print_function
from io import open
from six import iteritems
from six import iterkeys

from collections import OrderedDict

Expand Down Expand Up @@ -50,8 +55,8 @@ def configure_clang_format(self, apply):
try:
cformat_exe = subprocess.check_output(['which', 'clang-format']).strip()
except subprocess.CalledProcessError:
print "ERROR: Cannot find clang-format executable"
print " Please make sure it is in the PATH."
print("ERROR: Cannot find clang-format executable")
print(" Please make sure it is in the PATH.")
self.clang_format = []
return
self.clang_format = [cformat_exe, "-style=file", "-fallback-style=llvm"]
Expand All @@ -68,14 +73,14 @@ def process(self):

def process_components(self, content):
self.requested_classes += content.keys()
for name, components in content.iteritems():
for name, components in iteritems(content):
self.create_component(name, components["Members"])

def process_datatypes(self, content):
for name in content.iterkeys():
for name in iterkeys(content):
self.requested_classes.append(name)
self.requested_classes.append("%sData" % name)
for name, components in content.iteritems():
for name, components in iteritems(content):
self.create_data(name, components)
self.create_class(name, components)
self.create_collection(name, components)
Expand All @@ -85,21 +90,21 @@ def process_datatypes(self, content):
def print_report(self):
if not self.verbose:
return
pkl = open(os.path.join(thisdir, "figure.txt"))
pkl = open(os.path.join(thisdir, "figure.txt"), 'rb')
figure = pickle.load(pkl)
text = _text_ % (self.yamlfile,
len(self.created_classes),
self.install_dir
)
cntr = 0
print
print()
for figline, summaryline in zip(figure, text.splitlines()):
cntr += 1
print figline + summaryline
for i in xrange(cntr, len(figure)):
print figure[i]
print " 'Homage to the Square' - Josef Albers"
print
print(figline + summaryline)
for i in range(cntr, len(figure)):
print(figure[i])
print(" 'Homage to the Square' - Josef Albers")
print()

def get_template(self, filename):
templatefile = os.path.join(self.template_dir, filename)
Expand Down Expand Up @@ -252,14 +257,14 @@ def create_class(self, classname, definition):
klassname = klass
if "::" in klass:
mnamespace, klassname = klass.split("::")
if mnamespace not in forward_declarations_namespace.keys():
if mnamespace not in list(forward_declarations_namespace.keys()):
forward_declarations_namespace[mnamespace] = []

forward_declarations_namespace[mnamespace] += ["class %s;\n" %(klassname)]
forward_declarations_namespace[mnamespace] += ["class Const%s;\n" %(klassname)]
includes_cc.add(self._build_include(klassname))

for nsp in forward_declarations_namespace.iterkeys():
for nsp in iterkeys(forward_declarations_namespace):
if nsp != "":
forward_declarations += "namespace %s {\n" % nsp
forward_declarations += "".join(forward_declarations_namespace[nsp])
Expand Down Expand Up @@ -299,7 +304,7 @@ def create_class(self, classname, definition):
if( self.getSyntax ):
gname = "get" + name[:1].upper() + name[1:]
sname = "set" + name[:1].upper() + name[1:]
if name in all_members.keys():
if name in list(all_members.keys()):
raise Exception("'%s' clashes with another member name in class '%s', previously defined in %s" % (name, classname, all_members[name]))
all_members[name] = classname

Expand Down Expand Up @@ -472,17 +477,17 @@ def create_class(self, classname, definition):
extracode = ""
constextracode_declarations = ""
constextracode = ""
if definition.has_key("ExtraCode"):
if "ExtraCode" in definition:
extra = definition["ExtraCode"]
if( extra.has_key("declaration")):
if "declaration" in extra:
extracode_declarations = extra["declaration"].replace("{name}",rawclassname)
if( extra.has_key("implementation")):
if "implementation" in extra:
extracode = extra["implementation"].replace("{name}",rawclassname)
if( extra.has_key("const_declaration")):
if "const_declaration" in extra:
constextracode_declarations = extra["const_declaration"].replace("{name}","Const"+rawclassname)
extracode_declarations += "\n"
extracode_declarations += extra["const_declaration"]
if( extra.has_key("const_implementation")):
if "const_implementation" in extra:
constextracode = extra["const_implementation"].replace("{name}","Const"+rawclassname)
extracode += "\n"
extracode += extra["const_implementation"].replace("{name}",rawclassname)
Expand Down Expand Up @@ -582,14 +587,12 @@ def create_collection(self, classname, definition):
if t in comps.keys():
nCompMem = 0
compMemStr += ' ['
#print " found component: " , name , t , comps[ t ] , " #members: " , nCompMem
for cm in comps[t]["Members"]:
if cm != 'ExtraCode':
nCompMem += 1
compMemStr += ('%s,' % cm )
compMemStr += ']'
colW *= nCompMem
#print " found component: " , name , t , comps[ t ] , " #members: " , nCompMem
colName = name[:colW-2]
colName += compMemStr
colName +=":"
Expand Down Expand Up @@ -876,7 +879,7 @@ def create_component(self, classname, components):
else:
members += " ::%s::%s %s;\n" %(mnamespace, klassname, name)
self.component_members[classname].append(["::%s::%s" % (mnamespace, klassname), name])
if self.reader.components.has_key(klass):
if klass in self.reader.components:
includes.add(self._build_include(klassname))
if "std::array" in klass:
includes.add("#include <array>")
Expand Down Expand Up @@ -934,7 +937,7 @@ def create_obj(self, classname, definition):
if "::" in klass:
mnamespace, klassname = klass.split("::")
klassWithQualifier = "::"+mnamespace+"::Const"+klassname
if mnamespace not in forward_declarations_namespace.keys():
if mnamespace not in list(forward_declarations_namespace.keys()):
forward_declarations_namespace[mnamespace] = []
else:
klassWithQualifier = "Const"+klass
Expand All @@ -956,7 +959,7 @@ def create_obj(self, classname, definition):
set_relations += implementations["set_relations"].format(name=name, klass=klassWithQualifier)
delete_singlerelations+="\t\tif (m_%s != nullptr) delete m_%s;\n" % (name, name)

for nsp in forward_declarations_namespace.iterkeys():
for nsp in iterkeys(forward_declarations_namespace):
if nsp != "":
forward_declarations += "namespace %s {" % nsp
forward_declarations += "".join(forward_declarations_namespace[nsp])
Expand Down Expand Up @@ -1143,4 +1146,4 @@ def _join_set(aSet):
gen.process()
if gen.verbose:
for warning in gen.warnings:
print warning
print(warning)
17 changes: 11 additions & 6 deletions python/podio_config_reader.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@

from __future__ import absolute_import, unicode_literals, print_function
from io import open
from six import iteritems

import yaml
import copy
import re
Expand Down Expand Up @@ -78,8 +83,8 @@ def check_members(self, name, members):
theType = member["type"]
return # TODO
if theType not in self.buildin_types and \
theType not in self.datatypes.keys() and \
theType not in self.components.keys():
theType not in list(self.datatypes.keys()) and \
theType not in list(self.components.keys()):
raise Exception("%s defines a member of not allowed type %s"
% (name, theType))

Expand Down Expand Up @@ -132,7 +137,7 @@ def check_component(self, name, definition):
"which is not allowed in a component!")

def check_components(self, components):
for klassname, value in components.iteritems():
for klassname, value in iteritems(components):
self.check_component(klassname, value)


Expand Down Expand Up @@ -161,11 +166,11 @@ def read(self):
validator = ClassDefinitionValidator(content)
if "components" in content.keys():
validator.check_components(content["components"])
for klassname, value in content["components"].iteritems():
for klassname, value in iteritems(content["components"]):
component = {"Members": value}
self.components[klassname] = component
if "datatypes" in content:
for klassname, value in content["datatypes"].iteritems():
for klassname, value in iteritems(content["datatypes"]):
validator.check_datatype(klassname, value)
datatype = {}
datatype["Description"] = value["Description"]
Expand All @@ -191,5 +196,5 @@ def read(self):
value["ConstExtraCode"])
self.datatypes[klassname] = datatype
if "options" in content.keys():
for option, value in content["options"].iteritems():
for option, value in iteritems(content["options"]):
self.options[option] = value
1 change: 1 addition & 0 deletions python/podio_create_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#
#

from __future__ import absolute_import, unicode_literals

##########################
if __name__ == "__main__":
Expand Down
2 changes: 2 additions & 0 deletions python/podio_templates.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import unicode_literals

# flake8: noqa
declarations = {}
implementations = {}
Expand Down
7 changes: 5 additions & 2 deletions python/test_EventStore.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@

from __future__ import absolute_import, unicode_literals, print_function

import unittest
from EventStore import EventStore
import os
Expand Down Expand Up @@ -90,7 +93,7 @@ def test_chain(self):
numbers.append(evinfo[0].Number())
self.assertEqual(iev+1, 2*events.GetEntries())
# testing that numbers is [0, .. 1999, 0, .. 1999]
self.assertEqual(numbers, range(events.GetEntries())*2)
self.assertEqual(numbers, list(range(events.GetEntries()))*2)
# trying to go to an event beyond the last one
self.assertRaises(ValueError, self.store.__getitem__,
4001)
Expand All @@ -116,6 +119,6 @@ def test_no_file(self):
# creating example file for the tests
if not os.path.isfile('example.root'):
write = '{podio}/tests/write'.format(podio=os.environ['PODIO'])
print write
print(write)
call(write)
unittest.main()
8 changes: 6 additions & 2 deletions tests/read.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@


from __future__ import absolute_import, unicode_literals, print_function

import unittest
from EventStore import EventStore

Expand All @@ -7,10 +11,10 @@
store = EventStore([filename])
for i, event in enumerate(store):
if i % 1000 == 0:
print 'reading event', i
print('reading event', i)
evinfo = store.get("info")[0]
clusters = store.get("clusters")
for cluster in clusters:
for ihit in range(cluster.Hits_size()):
hit = cluster.Hits(ihit)
print ' Referenced hit has an energy of', hit.energy()
print(' Referenced hit has an energy of', hit.energy())

0 comments on commit 2e3b609

Please sign in to comment.