I have a generator function getElements in a class Reader() that yields all the elements out of an xml file. I also want to have a function getFeatures that only yields the elements with a feature tag.
How I tried it is to have a flag featuresOnly that is set to True when getFeatures is called, and in getFeatures call self.getElements, like this:
def getFeatures(self):
self.getFeaturesOnly = True
self.getElements()
This way in getElements() I only have to do
def getElements(self):
inFile = open(self.path)
for element in cElementTree.iterparse(inFile):
if self.getFeaturesOnly == True:
if element.tag == 'feature':
yield element
else:
yield element
inFile.close()
However, when I do this and run it
features = parseFeatureXML.Reader(filePath)
for element in features.getFeatures():#
print element
I get: TypeError: ‘NoneType’ object is not iterable
This is because getFeatures doesn’t contain a yield. Now, the way that I know how to solve this is to copy the code of getElements into getFeatures and only use the
if elementFunctions.getElmentTag(element) == 'feature':
in the getFeatures() function, but I rather not duplicate any code. So how would I be able to keep on generator function, and have a different function where I only specefy which tag I would like to get?
First things first: You have that error because you don’t return the generator
Meaning that you have to change:
with:
Cleared this, TBH I wouldn’t design my
Reader()class like this.I’d let the
getElementyield all the elements:And then
getFeatures()do the filtering: