How do i get worksets ids?

# document instance
doc = DocumentManager.Instance.CurrentDBDocument

# collect user created worksets
worksets = FilteredWorksetCollector(doc).OfKind(WorksetKind.UserWorkset).ToWorksets()

names = []
sets = []
ids = []

for nam in worksets:
    names.append(nam.Name)

for workset in worksets:
    sets.append(workset)

for num in worksets:
   ids.append(num.WorksetId)

OUT = names, sets, ids

I get names and Worksets very well, but in my Syntex regarding my Id there is something wrong!
If you have some Listcomprehensions, i am always happy regarding some “CodeCandy”! :slight_smile:

KR

Andreas

Shall we do a quick primer of sorts on Python’s list comprehension, and a few general Python best practices?

variable = [ action for object in objects ]

where:

variable is the name variable you want to store the list in.
[ starts the list which you want to store in the variable
action is the actual thing want to store in the list - could be a Revit object, a string, a number, or a list. This can be expressed as a direct call to a thing or an action to take on a thing, such as pulling the ID from a workset.
for indicates you’re no longer adding to the list, but want to perform the action a number of times based on the subsequent code
object is the single thing you want to iterate over - you’ll often but not always call this in the action. This is a single call variable which doesn’t persist outside of this line of code so you can reuse it without issue.
in indicates that you’re no longer adding to the object variable, but will be providing the source list which contains the object
objects is the source list which contains each object you want to drive your new list
] indicates that you’ve closed your list comprehension, this is usually the last bit in the line of code

Using that map above you can likely get to here:

But what you may not realize is that you can also use lists inside of any one variable. With that and a bit of cleanup on the imports to reduce the amount of code we transfer into the CLR, or from the CLR into Python, you can get your entire code down to 8 lines before annotation:

Adding in annotations to each line will ensure you understand your code - be as verbose as you want. , but will help you keep track of what you are up to when you come back to the code (this is inevitable - you build your own technical debt each time you start a new Python node), and will help others pick up code you’ve previously written. For me in this case that looks something like this:

5 Likes