Correctly wrap arbitrarily nested aggregates of entity instance attributes in IfcOpenShell-Python

This commit is contained in:
Thomas Krijnen
2015-06-17 19:46:11 +00:00
parent 6aabbd4a55
commit 76cbb79c75
@@ -51,16 +51,20 @@ class entity_instance(object):
return entity_instance.wrap_value(self.wrapped_data.get_inverse(name)) return entity_instance.wrap_value(self.wrapped_data.get_inverse(name))
else: raise AttributeError("entity instance of type '%s' has no attribute '%s'"%(self.wrapped_data.is_a(), name)) else: raise AttributeError("entity instance of type '%s' has no attribute '%s'"%(self.wrapped_data.is_a(), name))
@staticmethod @staticmethod
def walk(f, g, value):
if isinstance(value, (tuple, list)): return tuple(map(functools.partial(entity_instance.walk, f, g), value))
elif f(value): return g(value)
else: return value
@staticmethod
def wrap_value(v): def wrap_value(v):
wrap = lambda e: entity_instance(e) wrap = lambda e: entity_instance(e)
if isinstance(v, ifcopenshell_wrapper.entity_instance): return wrap(v) is_instance = lambda e: isinstance(e, ifcopenshell_wrapper.entity_instance)
elif isinstance(v, (tuple, list)) and len(v): return entity_instance.walk(is_instance, wrap, v)
classes = set(map(type, v)) @staticmethod
if {ifcopenshell_wrapper.entity_instance} == classes: return list(map(wrap, v)) def unwrap_value(v):
elif {list} == classes: unwrap = lambda e: e.wrapped_data
classes = set(map(type, v[0])) is_instance = lambda e: isinstance(e, entity_instance)
if {ifcopenshell_wrapper.entity_instance} == classes: return [list(map(wrap, x)) for x in v] return entity_instance.walk(is_instance, unwrap, v)
return v
def attribute_type(self, attr): def attribute_type(self, attr):
attr_idx = attr if isinstance(attr, int) else self.wrapped_data.get_argument_index(attr) attr_idx = attr if isinstance(attr, int) else self.wrapped_data.get_argument_index(attr)
return self.wrapped_data.get_argument_type(attr_idx) return self.wrapped_data.get_argument_type(attr_idx)
@@ -74,7 +78,7 @@ class entity_instance(object):
attr_type = self.attribute_type(idx).title().replace(' ', '') attr_type = self.attribute_type(idx).title().replace(' ', '')
attr_type = attr_type.replace('Binary', 'String') attr_type = attr_type.replace('Binary', 'String')
attr_type = attr_type.replace('Enumeration', 'String') attr_type = attr_type.replace('Enumeration', 'String')
getattr(self.wrapped_data, "setArgumentAs%s" % attr_type)(idx, value) getattr(self.wrapped_data, "setArgumentAs%s" % attr_type)(idx, entity_instance.unwrap_value(value))
def __len__(self): return len(self.wrapped_data) def __len__(self): return len(self.wrapped_data)
def __repr__(self): return repr(self.wrapped_data) def __repr__(self): return repr(self.wrapped_data)
def is_a(self, *args): return self.wrapped_data.is_a(*args) def is_a(self, *args): return self.wrapped_data.is_a(*args)