简体   繁体   中英

Simplify a series of repetitive functions with sort options

I have a series of functions in a module which are starting to become quite repetitive. Each function extracts a list, and has an optional boolean argument to sort the list before returning it. Feels like there ought to be a way to inherit the sorting from a parent function?

def get_electrical_equipment(sort_by_name = False):
    
    elements =  DB.FilteredElementCollector(revit.doc)\
        .OfCategory(DB.BuiltInCategory.OST_ElectricalEquipment)\
        .WhereElementIsNotElementType()\
        .ToElements()
        
    if sort_by_name: elements.sort(key=lambda x: x.Name)
    
    return elements

def get_panel_schedules(sort_by_name = False):
    elements = DB.FilteredElementCollector(revit.doc)\
        .WherePasses(DB.ElementClassFilter(DB.Electrical.PanelScheduleView))\
        .WhereElementIsNotElementType()\
        .ToElements()
        
    if sort_by_name: elements.sort(key=lambda x: x.Name)
    
    return elements

def get_panel_schedule_sheet_instances(sort_by_name = False):
    elements = DB.FilteredElementCollector(revit.doc)\
        .OfClass(DB.Electrical.PanelScheduleSheetInstance)\
        .ToElements()
        
    if sort_by_name: elements.sort(key=lambda x: x.Name)
    
    return elements

First of all, I think you can completely eliminate the call to ToElements . It is a waste of memory and computation time, as I have pointed out about 500 times in the past in the Revit API discussion forum and in The Building Coder, eg, in How to Distinguish Redundant Rooms . Now, to address your question, you can simply implement a common method get_elements_of_category_and_class taking a category and a class argument. Pass in either one or the other or both and execute OfClass and OfCategory checks on the filtered element collector, either one or the other or both, skipping evaluation of null -valued arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM