Skip to content

revit

Revit application wrapper.

Attributes

mlogger = get_logger(__name__) module-attribute

Classes

BaseWrapper(obj=None)

Bases: object

Base revit databse object wrapper.

Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def __init__(self, obj=None):
    self._wrapped = obj

Functions

unwrap()
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def unwrap(self):
    return self._wrapped
compare_attr(src, dest, attr_name, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attr(src, dest, attr_name, case_sensitive=False):
    if case_sensitive:
        return safe_strtype(getattr(src, attr_name, '')).lower() == \
               safe_strtype(getattr(dest, attr_name, '')).lower()
    else:
        return safe_strtype(getattr(src, attr_name)) == \
               safe_strtype(getattr(dest, attr_name))
compare_attrs(src, dest, attr_names, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attrs(src, dest, attr_names, case_sensitive=False):
    return [BaseWrapper.compare_attr(src,
                                     dest,
                                     x,
                                     case_sensitive=case_sensitive)
            for x in attr_names]

ElementWrapper(element)

Bases: BaseWrapper

Revit element wrapper.

Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def __init__(self, element):
    super(ElementWrapper, self).__init__(element)
    if not isinstance(self._wrapped, DB.Element):
        raise PyRevitException('Can not wrap object that are not '
                               'derived from Element.')

Attributes

assoc_doc property
name property
symbol_name property
family_name property
id property
unique_id property
workset_id property
mark property
location property
x property
y property
z property

Functions

unwrap()
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def unwrap(self):
    return self._wrapped
compare_attr(src, dest, attr_name, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attr(src, dest, attr_name, case_sensitive=False):
    if case_sensitive:
        return safe_strtype(getattr(src, attr_name, '')).lower() == \
               safe_strtype(getattr(dest, attr_name, '')).lower()
    else:
        return safe_strtype(getattr(src, attr_name)) == \
               safe_strtype(getattr(dest, attr_name))
compare_attrs(src, dest, attr_names, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attrs(src, dest, attr_names, case_sensitive=False):
    return [BaseWrapper.compare_attr(src,
                                     dest,
                                     x,
                                     case_sensitive=case_sensitive)
            for x in attr_names]
get_param(param_name)
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def get_param(self, param_name):
    return self._wrapped.LookupParameter(param_name)
safe_get_param(param_name, default=None)
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def safe_get_param(self, param_name, default=None):
    try:
        return self._wrapped.LookupParameter(param_name)
    except Exception:
        return default

ExternalRef(link, extref)

Bases: ElementWrapper

External reference wraper.

Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def __init__(self, link, extref):
    super(ExternalRef, self).__init__(link)
    self._extref = extref

Attributes

assoc_doc property
symbol_name property
family_name property
id property
unique_id property
workset_id property
mark property
location property
x property
y property
z property
name property
linktype property
path property

Functions

unwrap()
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def unwrap(self):
    return self._wrapped
compare_attr(src, dest, attr_name, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attr(src, dest, attr_name, case_sensitive=False):
    if case_sensitive:
        return safe_strtype(getattr(src, attr_name, '')).lower() == \
               safe_strtype(getattr(dest, attr_name, '')).lower()
    else:
        return safe_strtype(getattr(src, attr_name)) == \
               safe_strtype(getattr(dest, attr_name))
compare_attrs(src, dest, attr_names, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attrs(src, dest, attr_names, case_sensitive=False):
    return [BaseWrapper.compare_attr(src,
                                     dest,
                                     x,
                                     case_sensitive=case_sensitive)
            for x in attr_names]
get_param(param_name)
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def get_param(self, param_name):
    return self._wrapped.LookupParameter(param_name)
safe_get_param(param_name, default=None)
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def safe_get_param(self, param_name, default=None):
    try:
        return self._wrapped.LookupParameter(param_name)
    except Exception:
        return default
reload()
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def reload(self):
    return self._wrapped.Reload()

ProjectParameter(param_def, param_binding=None, param_ext_def=False)

Bases: BaseWrapper

Project parameter wrapper.

Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def __init__(self, param_def, param_binding=None, param_ext_def=False):
    super(ProjectParameter, self).__init__()
    self.param_def = param_def
    self.param_binding = param_binding
    self.param_binding_type = self._determine_binding_type()

    self.shared = False
    self.param_ext_def = None
    self.param_guid = ''
    if param_ext_def:
        self.shared = True
        self.param_ext_def = param_ext_def
        self.param_guid = self.param_ext_def.GUID.ToString()

    self.name = self.param_def.Name

    # Revit <2017 does not have the Id parameter
    self.param_id = getattr(self.param_def, 'Id', None)

    if HOST_APP.is_exactly(2021):
        # Revit >2021 does not have the UnitType property
        self.unit_type = self.param_def.GetSpecTypeId()
        self.param_type = self.param_def.ParameterType
        self.param_group = self.param_def.ParameterGroup
    elif HOST_APP.is_newer_than(2022, or_equal=True):
        # GetSpecTypeId() Removed in Revit 2022
        self.unit_type = self.param_def.GetDataType()
        # Revit >2022 does not have the ParameterType property
        self.param_type = self.param_def.GetDataType()
        # ParameterGroup deprecated
        self.param_group = self.param_def.GetGroupTypeId().TypeId
    else:
        self.unit_type = self.param_def.UnitType
        self.param_type = self.param_def.ParameterType
        self.param_group = self.param_def.ParameterGroup

Attributes

param_def = param_def instance-attribute
param_binding = param_binding instance-attribute
param_binding_type = self._determine_binding_type() instance-attribute
shared = False instance-attribute
param_ext_def = None instance-attribute
param_guid = '' instance-attribute
name = self.param_def.Name instance-attribute
param_id = getattr(self.param_def, 'Id', None) instance-attribute
unit_type = self.param_def.GetSpecTypeId() instance-attribute
param_type = self.param_def.ParameterType instance-attribute
param_group = self.param_def.ParameterGroup instance-attribute

Functions

unwrap()
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def unwrap(self):
    return self._wrapped
compare_attr(src, dest, attr_name, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attr(src, dest, attr_name, case_sensitive=False):
    if case_sensitive:
        return safe_strtype(getattr(src, attr_name, '')).lower() == \
               safe_strtype(getattr(dest, attr_name, '')).lower()
    else:
        return safe_strtype(getattr(src, attr_name)) == \
               safe_strtype(getattr(dest, attr_name))
compare_attrs(src, dest, attr_names, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attrs(src, dest, attr_names, case_sensitive=False):
    return [BaseWrapper.compare_attr(src,
                                     dest,
                                     x,
                                     case_sensitive=case_sensitive)
            for x in attr_names]

ProjectInfo(doc)

Bases: BaseWrapper

Project information.

Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def __init__(self, doc):
    super(ProjectInfo, self).__init__()
    self._doc = doc

Attributes

name property
number property
address property
author property
building_name property
client_name property
issue_date property
org_name property
org_desc property
status property
location property
path property
filename property

Functions

unwrap()
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def unwrap(self):
    return self._wrapped
compare_attr(src, dest, attr_name, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attr(src, dest, attr_name, case_sensitive=False):
    if case_sensitive:
        return safe_strtype(getattr(src, attr_name, '')).lower() == \
               safe_strtype(getattr(dest, attr_name, '')).lower()
    else:
        return safe_strtype(getattr(src, attr_name)) == \
               safe_strtype(getattr(dest, attr_name))
compare_attrs(src, dest, attr_names, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attrs(src, dest, attr_names, case_sensitive=False):
    return [BaseWrapper.compare_attr(src,
                                     dest,
                                     x,
                                     case_sensitive=case_sensitive)
            for x in attr_names]

XYZPoint(obj=None)

Bases: BaseWrapper

Wrapper for XYZ point.

Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def __init__(self, obj=None):
    self._wrapped = obj

Attributes

x property
y property
z property

Functions

unwrap()
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
def unwrap(self):
    return self._wrapped
compare_attr(src, dest, attr_name, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attr(src, dest, attr_name, case_sensitive=False):
    if case_sensitive:
        return safe_strtype(getattr(src, attr_name, '')).lower() == \
               safe_strtype(getattr(dest, attr_name, '')).lower()
    else:
        return safe_strtype(getattr(src, attr_name)) == \
               safe_strtype(getattr(dest, attr_name))
compare_attrs(src, dest, attr_names, case_sensitive=False) staticmethod
Source code in pyrevitlib/pyrevit/revit/db/__init__.py
@staticmethod
def compare_attrs(src, dest, attr_names, case_sensitive=False):
    return [BaseWrapper.compare_attr(src,
                                     dest,
                                     x,
                                     case_sensitive=case_sensitive)
            for x in attr_names]

Transaction(name=None, doc=None, clear_after_rollback=False, show_error_dialog=False, swallow_errors=False, log_errors=True, nested=False)

Adds a context manager around Revit Transaction object.

Runs Transaction.Start() and Transaction.Commit() before and after the context. Automatically rolls back if exception is raised.

```python with Transaction('Move Wall'): wall.DoSomething()

with Transaction('Move Wall') as action:
wall.DoSomething()
assert action.status == ActionStatus.Started  # True
assert action.status == ActionStatus.Committed    # True
```
Source code in pyrevitlib/pyrevit/revit/db/transaction.py
def __init__(self, name=None,
             doc=None,
             clear_after_rollback=False,
             show_error_dialog=False,
             swallow_errors=False,
             log_errors=True,
             nested=False):
    doc = doc or DOCS.doc
    # create nested transaction if one is already open
    if doc.IsModifiable or nested:
        self._rvtxn = \
            DB.SubTransaction(doc)
    else:
        self._rvtxn = \
            DB.Transaction(doc, name if name else DEFAULT_TRANSACTION_NAME)
        self._fhndlr_ops = self._rvtxn.GetFailureHandlingOptions()
        self._fhndlr_ops = \
            self._fhndlr_ops.SetClearAfterRollback(clear_after_rollback)
        self._fhndlr_ops = \
            self._fhndlr_ops.SetForcedModalHandling(show_error_dialog)
        if swallow_errors:
            self._fhndlr_ops = \
                self._fhndlr_ops.SetFailuresPreprocessor(
                    failure.FailureSwallower()
                    )
        self._rvtxn.SetFailureHandlingOptions(self._fhndlr_ops)
    self._logerror = log_errors

Attributes

name property writable
status property

Functions

has_started()
Source code in pyrevitlib/pyrevit/revit/db/transaction.py
def has_started(self):
    return self._rvtxn.HasStarted()
has_ended()
Source code in pyrevitlib/pyrevit/revit/db/transaction.py
def has_ended(self):
    return self._rvtxn.HasEnded()

DryTransaction(name=None, doc=None, clear_after_rollback=False, show_error_dialog=False, swallow_errors=False, log_errors=True, nested=False)

Bases: Transaction

Wrapper to a transaction that doesn't commit anything (dry-run).

Source code in pyrevitlib/pyrevit/revit/db/transaction.py
def __init__(self, name=None,
             doc=None,
             clear_after_rollback=False,
             show_error_dialog=False,
             swallow_errors=False,
             log_errors=True,
             nested=False):
    doc = doc or DOCS.doc
    # create nested transaction if one is already open
    if doc.IsModifiable or nested:
        self._rvtxn = \
            DB.SubTransaction(doc)
    else:
        self._rvtxn = \
            DB.Transaction(doc, name if name else DEFAULT_TRANSACTION_NAME)
        self._fhndlr_ops = self._rvtxn.GetFailureHandlingOptions()
        self._fhndlr_ops = \
            self._fhndlr_ops.SetClearAfterRollback(clear_after_rollback)
        self._fhndlr_ops = \
            self._fhndlr_ops.SetForcedModalHandling(show_error_dialog)
        if swallow_errors:
            self._fhndlr_ops = \
                self._fhndlr_ops.SetFailuresPreprocessor(
                    failure.FailureSwallower()
                    )
        self._rvtxn.SetFailureHandlingOptions(self._fhndlr_ops)
    self._logerror = log_errors

Attributes

name property writable
status property

Functions

has_started()
Source code in pyrevitlib/pyrevit/revit/db/transaction.py
def has_started(self):
    return self._rvtxn.HasStarted()
has_ended()
Source code in pyrevitlib/pyrevit/revit/db/transaction.py
def has_ended(self):
    return self._rvtxn.HasEnded()

TransactionGroup(name=None, doc=None, assimilate=True, log_errors=True)

Transactions group with context manager.

Source code in pyrevitlib/pyrevit/revit/db/transaction.py
def __init__(self, name=None, doc=None, assimilate=True, log_errors=True):
    self._rvtxn_grp = \
        DB.TransactionGroup(doc or DOCS.doc,
                            name if name else DEFAULT_TRANSACTION_NAME)
    self.assimilate = assimilate
    self._logerror = log_errors

Attributes

assimilate = assimilate instance-attribute
name property writable
status property

Functions

has_started()
Source code in pyrevitlib/pyrevit/revit/db/transaction.py
def has_started(self):
    return self._rvtxn_grp.HasStarted()
has_ended()
Source code in pyrevitlib/pyrevit/revit/db/transaction.py
def has_ended(self):
    return self._rvtxn_grp.HasEnded()

RevitWrapper()

Bases: ModuleType

Revit application wrapper.

Source code in pyrevitlib/pyrevit/revit/__init__.py
def __init__(self):
    pass

Attributes

uidoc property

Active UI Document.

doc property

Active document.

docs property

Active documents.

active_view property writable

Active view.

active_ui_view property

Active UI view.

servers property

Available revit server names.

Functions

open_doc(doc_path) staticmethod

Open document at given path.

Parameters:

Name Type Description Default
doc_path str

document file path

required

Returns:

Type Description
Document

opened document

Source code in pyrevitlib/pyrevit/revit/__init__.py
@staticmethod
def open_doc(doc_path):
    """Open document at given path.

    Args:
        doc_path (str): document file path

    Returns:
        (DB.Document): opened document
    """
    return HOST_APP.app.OpenDocumentFile(doc_path)
close_doc(doc) staticmethod

Close given document.

Parameters:

Name Type Description Default
doc Document

document

required
Source code in pyrevitlib/pyrevit/revit/__init__.py
@staticmethod
def close_doc(doc):
    """Close given document.

    Args:
        doc (DB.Document): document
    """
    return doc.Close()
post_command(command_id) staticmethod

Request Revit to run a command.

Parameters:

Name Type Description Default
command_id str

command identifier e.g. ID_REVIT_SAVE_AS_TEMPLATE

required
Source code in pyrevitlib/pyrevit/revit/__init__.py
@staticmethod
def post_command(command_id):
    """Request Revit to run a command.

    Args:
        command_id (str): command identifier e.g. ID_REVIT_SAVE_AS_TEMPLATE
    """
    HOST_APP.post_command(command_id)

ErrorSwallower(log_errors=True)

Suppresses warnings during script execution.

Examples:

with ErrorSwallower() as swallower:
    for fam in families:
        revit.doc.EditFamily(fam)
        if swallower.get_swallowed():
            logger.warn("Warnings swallowed")
Source code in pyrevitlib/pyrevit/revit/__init__.py
def __init__(self, log_errors=True):
    self._fswallower = failure.FailureSwallower()
    self._logerror = log_errors

Functions

on_failure_processing(_, event_args)

Failure processing event handler.

Source code in pyrevitlib/pyrevit/revit/__init__.py
def on_failure_processing(self, _, event_args):
    """Failure processing event handler."""
    try:
        failure_accesssor = event_args.GetFailuresAccessor()
        mlogger.debug('request for failure processing...')
        result = event_args.GetProcessingResult()
        mlogger.debug('current failure processing result: %s', result)
        result = self._fswallower.preprocess_failures(failure_accesssor)
        mlogger.debug('setting failure processing results to: %s', result)
        event_args.SetProcessingResult(result)
    except Exception as fpex:
        mlogger.error('Error occured while processing failures. | %s', fpex)
get_swallowed_errors()

Return swallowed errors.

Source code in pyrevitlib/pyrevit/revit/__init__.py
def get_swallowed_errors(self):
    """Return swallowed errors."""
    return self._fswallower.get_swallowed_failures()
reset()

Reset swallowed errors.

Source code in pyrevitlib/pyrevit/revit/__init__.py
def reset(self):
    """Reset swallowed errors."""
    self._fswallower.reset()

Functions

carryout(name, doc=None)

Transaction Decorator.

Decorate any function with @doc.carryout('Txn name') and the funciton will run within an Transaction context.

Parameters:

Name Type Description Default
name str

Name of the Transaction

required
doc Document

Revit document

None
@doc.carryout('Do Something')
def set_some_parameter(wall, value):
    wall.parameters['Comments'].value = value


set_some_parameter(wall, value)
Source code in pyrevitlib/pyrevit/revit/db/transaction.py
def carryout(name, doc=None):
    """Transaction Decorator.

    Decorate any function with ``@doc.carryout('Txn name')``
    and the funciton will run within an Transaction context.

    Args:
        name (str): Name of the Transaction
        doc (Document): Revit document

    ```python
    @doc.carryout('Do Something')
    def set_some_parameter(wall, value):
        wall.parameters['Comments'].value = value


    set_some_parameter(wall, value)
    ```
    """
    from functools import wraps

    def wrap(f):
        @wraps(f)
        def wrapped_f(*args, **kwargs):
            with Transaction(name, doc=doc):
                return_value = f(*args, **kwargs)
            return return_value
        return wrapped_f
    return wrap

serialize(api_object)

Source code in pyrevitlib/pyrevit/revit/db/pickling.py
def serialize(api_object):
    mlogger.debug('Attemping to serialize: %s', api_object)

    # wrap none in a none serializer for none values
    if api_object is None:
        return NoneSerializer()

    # make sure given type is a Revit API type
    if not api.is_api_object(api_object):
        raise PyRevitException("Only Revit API types are supported.")

    # get available serializers
    serializers = coreutils.get_all_subclasses(
        [Serializable, EnumSerializable]
        )

    # pick the compatible serializer
    try:
        compatible_serializer = \
            next(
                x for x in serializers
                if x.api_types and isinstance(api_object, x.api_types)
                )
        mlogger.debug('Serializer found for: %s', api_object)
        return compatible_serializer(api_object)
    except StopIteration:
        mlogger.debug('Serializer not found for: %s', api_object)
        # if no deserializer found,
        # see if given data is iterable
        # NOTE: commented this out since .serialize should only get api objects
        # if isinstance(api_object, Iterable):
        #     mlogger.debug('Iterating over: %s', api_object)
        #     return _serialize_items(api_object)

        # otherwise throw an exception
        raise PyRevitException(
            "No serializers have been implemented for \"%s\"" % repr(api_object)
            )

deserialize(python_object)

Source code in pyrevitlib/pyrevit/revit/db/pickling.py
def deserialize(python_object):
    if isinstance(python_object, Iterable):
        result_list = []
        for python_item in python_object:
            result_list.append(deserialize(python_item))
        return result_list

    if isinstance(python_object, Serializable):
        return python_object.deserialize()

get_journals_folder()

Source code in pyrevitlib/pyrevit/revit/journals.py
def get_journals_folder():
    return op.dirname(HOST_APP.app.RecordingJournalFilename)

get_current_journal_file()

Source code in pyrevitlib/pyrevit/revit/journals.py
def get_current_journal_file():
    return HOST_APP.app.RecordingJournalFilename

get_current_session_id()

Source code in pyrevitlib/pyrevit/revit/journals.py
def get_current_session_id():
    re_finder = re.compile(r'.*>Session\s+(\$.{8}).*')
    journal_file = get_current_journal_file()
    with open(journal_file, "r") as jfile:
        for jline in reversed(jfile.readlines()):
            match = re_finder.match(jline)
            if match:
                return match.groups()[0]

pick_element(message='')

Asks the user to pick an element.

Parameters:

Name Type Description Default
message str

An optional message to display.

''

Returns:

Type Description
Element

element selected by the user.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_element(message=''):
    """Asks the user to pick an element.

    Args:
        message (str): An optional message to display.

    Returns:
        (Element): element selected by the user.
    """
    return _pick_obj(UI.Selection.ObjectType.Element,
                     message)

pick_element_by_category(cat_name_or_builtin, message='')

Returns the element of the specified category picked by the user.

Parameters:

Name Type Description Default
cat_name_or_builtin str

name or built-in category of the element to pick.

required
message str

message to display on selection. Defaults to ''.

''

Returns:

Type Description
Element

picked element.

Raises:

Type Description
PyRevitException

If no category matches the specified name or builtin.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_element_by_category(cat_name_or_builtin, message=''):
    """Returns the element of the specified category picked by the user.

    Args:
        cat_name_or_builtin (str): name or built-in category of the element
            to pick.
        message (str, optional): message to display on selection.
            Defaults to ''.

    Returns:
        (Element): picked element.

    Raises:
        PyRevitException: If no category matches the specified name or builtin.
    """
    category = query.get_category(cat_name_or_builtin)
    if category:
        pick_filter = PickByCategorySelectionFilter(category.Id)
        return _pick_obj(UI.Selection.ObjectType.Element,
                         message,
                         selection_filter=pick_filter)
    else:
        raise PyRevitException("Can not determine category id from: {}"
                               .format(cat_name_or_builtin))

pick_elementpoint(message='', world=False)

Returns the element point selected by the user.

Parameters:

Name Type Description Default
message str

message to display. Defaults to ''.

''
world bool

whether to use world coordinates. Defaults to False.

False

Returns:

Type Description
PointOnElement

The selected point.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_elementpoint(message='', world=False):
    """Returns the element point selected by the user.

    Args:
        message (str, optional): message to display. Defaults to ''.
        world (bool, optional): whether to use world coordinates. Defaults to False.

    Returns:
        (PointOnElement): The selected point.
    """
    return _pick_obj(UI.Selection.ObjectType.PointOnElement,
                     message,
                     world=world)

pick_edge(message='')

Returns the edge selected by the user.

Parameters:

Name Type Description Default
message str

message to display. Defaults to ''.

''

Returns:

Type Description
Edge

The selected edge.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_edge(message=''):
    """Returns the edge selected by the user.

    Args:
        message (str, optional): message to display. Defaults to ''.

    Returns:
        (Edge): The selected edge.
    """
    return _pick_obj(UI.Selection.ObjectType.Edge,
                     message)

pick_face(message='')

Returns the face selected by the user.

Parameters:

Name Type Description Default
message str

message to display. Defaults to ''.

''

Returns:

Type Description
Face

The selected face.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_face(message=''):
    """Returns the face selected by the user.

    Args:
        message (str, optional): message to display. Defaults to ''.

    Returns:
        (Face): The selected face.
    """
    return _pick_obj(UI.Selection.ObjectType.Face,
                     message)

pick_linked(message='')

Returns the linked element selected by the user.

Parameters:

Name Type Description Default
message str

message to display. Defaults to ''.

''

Returns:

Type Description
LinkedElement

The selected linked element.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_linked(message=''):
    """Returns the linked element selected by the user.

    Args:
        message (str, optional): message to display. Defaults to ''.

    Returns:
        (LinkedElement): The selected linked element.
    """
    return _pick_obj(UI.Selection.ObjectType.LinkedElement,
                     message)

pick_elements(message='')

Asks the user to pick multiple elements.

Parameters:

Name Type Description Default
message str

An optional message to display.

''

Returns:

Type Description
list[Element]

elements selected by the user.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_elements(message=''):
    """Asks the user to pick multiple elements.

    Args:
        message (str): An optional message to display.

    Returns:
        (list[Element]): elements selected by the user.
    """
    return _pick_obj(UI.Selection.ObjectType.Element,
                     message,
                     multiple=True)

pick_elements_by_category(cat_name_or_builtin, message='')

Returns the elements of the specified category picked by the user.

Parameters:

Name Type Description Default
cat_name_or_builtin str

name or built-in category of the elements to pick.

required
message str

message to display on selection. Defaults to ''.

''

Returns:

Type Description
list[Element]

picked elements.

Raises:

Type Description
PyRevitException

If no category matches the specified name or builtin.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_elements_by_category(cat_name_or_builtin, message=''):
    """Returns the elements of the specified category picked by the user.

    Args:
        cat_name_or_builtin (str): name or built-in category of the elements
            to pick.
        message (str, optional): message to display on selection.
            Defaults to ''.

    Returns:
        (list[Element]): picked elements.

    Raises:
        PyRevitException: If no category matches the specified name or builtin.
    """
    category = query.get_category(cat_name_or_builtin)
    if category:
        pick_filter = PickByCategorySelectionFilter(category.Id)
        return _pick_obj(UI.Selection.ObjectType.Element,
                         message,
                         multiple=True,
                         selection_filter=pick_filter)
    else:
        raise PyRevitException("Can not determine category id from: {}"
                               .format(cat_name_or_builtin))

get_picked_elements(message='')

Allows the user to pick multple elements, one at a time.

It keeps asking the user to pick an element until no elements are selected.

Parameters:

Name Type Description Default
message str

The message to display. Defaults to ''.

''

Yields:

Type Description
Element

selected element

Source code in pyrevitlib/pyrevit/revit/selection.py
def get_picked_elements(message=''):
    """Allows the user to pick multple elements, one at a time.

    It keeps asking the user to pick an element until no elements are selected.

    Args:
        message (str, optional): The message to display. Defaults to ''.

    Yields:
        (DB.Element): selected element
    """
    picked_element = True
    while picked_element:
        picked_element = pick_element(message=message)
        if not picked_element:
            break
        yield picked_element

get_picked_elements_by_category(cat_name_or_builtin, message='')

Pick elements by category.

Keeps asking the user to pick an element until no elements are selected.

Parameters:

Name Type Description Default
cat_name_or_builtin str

category name or built-in category.

required
message str

message to display while picking elements.

''

Yields:

Type Description
Element

The picked elements from the specified category.

Source code in pyrevitlib/pyrevit/revit/selection.py
def get_picked_elements_by_category(cat_name_or_builtin, message=''):
    """Pick elements by category.

    Keeps asking the user to pick an element until no elements are selected.

    Args:
        cat_name_or_builtin (str): category name or built-in category.
        message (str, optional): message to display while picking elements.

    Yields:
        (DB.Element): The picked elements from the specified category.
    """
    picked_element = True
    while picked_element:
        picked_element = pick_element_by_category(cat_name_or_builtin,
                                                  message=message)
        if not picked_element:
            break
        yield picked_element

pick_elementpoints(message='', world=False)

Selects element points.

Parameters:

Name Type Description Default
message str

The message to display when selecting element points.

''
world bool

Select points in world coordinates. Defaults to False.

False

Returns:

Type Description
list[PointOnElement]

selected element points.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_elementpoints(message='', world=False):
    """Selects element points.

    Args:
        message (str): The message to display when selecting element points.
        world (bool, optional): Select points in world coordinates. Defaults to False.

    Returns:
        (list[PointOnElement]): selected element points.
    """
    return _pick_obj(UI.Selection.ObjectType.PointOnElement,
                     message,
                     multiple=True, world=world)

pick_edges(message='')

Selects edges.

Parameters:

Name Type Description Default
message str

The message to display when selecting edges.

''

Returns:

Type Description
list[Edge]

selected edges.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_edges(message=''):
    """Selects edges.

    Args:
        message (str): The message to display when selecting edges.

    Returns:
        (list[Edge]): selected edges.
    """
    return _pick_obj(UI.Selection.ObjectType.Edge,
                     message,
                     multiple=True)

pick_faces(message='')

Selects faces.

Parameters:

Name Type Description Default
message str

The message to display when selecting the faces.

''

Returns:

Type Description
list[Face]

selected faces.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_faces(message=''):
    """Selects faces.

    Args:
        message (str): The message to display when selecting the faces.

    Returns:
        (list[Face]): selected faces.
    """
    return _pick_obj(UI.Selection.ObjectType.Face,
                     message,
                     multiple=True)

pick_linkeds(message='')

Selects linked elements.

Parameters:

Name Type Description Default
message str

The message to display when selecting linked elements.

''

Returns:

Type Description
list[LinkedElement]

selected linked elements.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_linkeds(message=''):
    """Selects linked elements.

    Args:
        message (str): The message to display when selecting linked elements.

    Returns:
        (list[LinkedElement]): selected linked elements.
    """
    return _pick_obj(UI.Selection.ObjectType.LinkedElement,
                     message,
                     multiple=True)

pick_point(message='')

Pick a point from the user interface.

Parameters:

Name Type Description Default
message str

A message to display when prompting for the point.

''

Returns:

Type Description
tuple or None

A tuple representing the picked point as (x, y, z) coordinates, or None if no point was picked or an error occurred.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_point(message=''):
    """Pick a point from the user interface.

    Args:
        message (str): A message to display when prompting for the point.

    Returns:
        (tuple or None): A tuple representing the picked point as (x, y, z)
            coordinates, or None if no point was picked or an error occurred.
    """
    try:
        return HOST_APP.uidoc.Selection.PickPoint(message)
    except Exception:
        return None

pick_rectangle(message='', pick_filter=None)

Picks elements from the user interface by specifying a rectangular area.

Parameters:

Name Type Description Default
message str

A custom message to display when prompting the user to pick elements. Default is an empty string.

''
pick_filter object

An object specifying the filter to apply when picking elements. Default is None.

None

Returns:

Type Description
list[ElementId]

The selected elements.

Source code in pyrevitlib/pyrevit/revit/selection.py
def pick_rectangle(message='', pick_filter=None):
    """Picks elements from the user interface by specifying a rectangular area.

    Args:
        message (str, optional): A custom message to display when prompting
            the user to pick elements. Default is an empty string.
        pick_filter (object, optional): An object specifying the filter to apply
            when picking elements. Default is None.

    Returns:
        (list[DB.ElementId]): The selected elements.
    """
    if pick_filter:
        return HOST_APP.uidoc.Selection.PickElementsByRectangle(pick_filter,
                                                                message)
    else:
        return HOST_APP.uidoc.Selection.PickElementsByRectangle(message)

get_selection_category_set()

Returns a CategorySet with the categories of the selected elements.

Returns:

Type Description
CategorySet

categories of the selected elements.

Source code in pyrevitlib/pyrevit/revit/selection.py
def get_selection_category_set():
    """Returns a CategorySet with the categories of the selected elements.

    Returns:
        (CategorySet): categories of the selected elements.
    """
    selection = ElementSelection()
    cset = DB.CategorySet()
    for element in selection:
        cset.Insert(element.Category)
    return cset

get_selection()

Returns the current selected items.

Returns:

Type Description
ElementSelection

the current selected items

Source code in pyrevitlib/pyrevit/revit/selection.py
def get_selection():
    """Returns the current selected items.

    Returns:
        (ElementSelection): the current selected items
    """
    return ElementSelection()

get_imported_symbol(symbol_name)

Geth an imported symbol by its name.

Parameters:

Name Type Description Default
symbol_name str

symbol name

required

Returns:

Type Description
Any

imported symbol, if found, None otherwise.

Source code in pyrevitlib/pyrevit/revit/__init__.py
def get_imported_symbol(symbol_name):
    """Geth an imported symbol by its name.

    Args:
        symbol_name (str): symbol name

    Returns:
        (Any): imported symbol, if found, None otherwise.
    """
    return globals().get(symbol_name, None)