I guess you want
print results
for return
["Sparcy", "Libs", "Darwin", "Aaple"]
- Printing a list shows a representation of its elements.
repr(elt) is defined by type(elt).__repr__ .- Since in this case the elements are classes, you need to set
__repr__ for the class type.
import re inputlist = '''\ Project="Sparcy" Desc="" Project="Libs" Desc="" Project="Darwin" Desc="" Project="Aaple" Desc="The big project" Site="Phoenix" Protocol="Cheese"''' regex = re.compile('([^ =]+) *= *("[^"]*"|[^ ]*)') results = [] for project in inputlist.split("\n"): items = [ (k.strip(), v.strip()) for k, v in regex.findall(project)] if len(items) < 2: print("Houston we have a problem - Only %sk/v pair found for %s" % (len(items), project)) continue item_dict = dict(items[1:]) item_dict['name'] = items[0][1] projectname=items[0][0] metametaklass=type('meta_'+projectname,(type,),{'__repr__':lambda cls: cls.__name__}) metaklass=metametaklass(projectname,(type,),{'__repr__':lambda cls: cls.name}) klass=metaklass(projectname+'_class', (object,), item_dict) results.append(klass) print(results)
gives
["Sparcy", "Libs", "Darwin", "Aaple", "Phoenix"]
and
for result in results: print(type(result)) print(result) print('-'*80)
gives
Project "Sparcy" -------------------------------------------------------------------------------- Project "Libs" -------------------------------------------------------------------------------- Project "Darwin" -------------------------------------------------------------------------------- Project "Aaple" -------------------------------------------------------------------------------- Site "Phoenix" --------------------------------------------------------------------------------
PS. Note that this is a perversion of __repr__ , since the repr object of the object must be an unambiguous string representation of the object. That is, it is assumed that enough information is available to reproduce the object. You should probably define another print function instead of messing with metaclasses.
source share