Skip to content

api

Public API

Anything that isn't defined here is INTERNAL and unreliable for external use.

Loader

Bases: LoaderPlugin

Source code in client/ayon_maya/api/plugin.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
class Loader(LoaderPlugin):
    hosts = ["maya"]
    settings_category = SETTINGS_CATEGORY
    load_settings = {}  # defined in settings

    use_ayon_entity_uri = False

    @classmethod
    def filepath_from_context(cls, context):
        # TODO: This is a 1:1 copy from ayon-houdini and may be good to
        #  refactor and de-duplicate across the codebase, e.g. to core
        if cls.use_ayon_entity_uri:
            return get_ayon_entity_uri_from_representation_context(context)

        return super().filepath_from_context(context)

    @classmethod
    def apply_settings(cls, project_settings):
        super(Loader, cls).apply_settings(project_settings)
        cls.load_settings = project_settings['maya']['load']

    def get_custom_namespace_and_group(self, context, options, loader_key):
        """Queries Settings to get custom template for namespace and group.

        Group template might be empty >> this forces to not wrap imported items
        into separate group.

        Args:
            context (dict)
            options (dict): artist modifiable options from dialog
            loader_key (str): key to get separate configuration from Settings
                ('reference_loader'|'import_loader')
        """

        options["attach_to_root"] = True
        custom_naming = self.load_settings[loader_key]

        if not custom_naming["namespace"]:
            raise LoadError("No namespace specified in "
                            "Maya ReferenceLoader settings")
        elif not custom_naming["group_name"]:
            self.log.debug("No custom group_name, no group will be created.")
            options["attach_to_root"] = False

        folder_entity = context["folder"]
        product_entity = context["product"]
        product_name = product_entity["name"]
        product_type = product_entity["productType"]
        formatting_data = {
            "asset_name": folder_entity["name"],
            "asset_type": "asset",
            "folder": {
                "name": folder_entity["name"],
            },
            "subset": product_name,
            "product": {
                "name": product_name,
                "type": product_type,
            },
            "family": product_type
        }

        custom_namespace = custom_naming["namespace"].format(
            **formatting_data
        )

        custom_group_name = custom_naming["group_name"].format(
            **formatting_data
        )

        return custom_group_name, custom_namespace, options

get_custom_namespace_and_group(context, options, loader_key)

Queries Settings to get custom template for namespace and group.

Group template might be empty >> this forces to not wrap imported items into separate group.

Parameters:

Name Type Description Default
options dict

artist modifiable options from dialog

required
loader_key str

key to get separate configuration from Settings ('reference_loader'|'import_loader')

required
Source code in client/ayon_maya/api/plugin.py
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
def get_custom_namespace_and_group(self, context, options, loader_key):
    """Queries Settings to get custom template for namespace and group.

    Group template might be empty >> this forces to not wrap imported items
    into separate group.

    Args:
        context (dict)
        options (dict): artist modifiable options from dialog
        loader_key (str): key to get separate configuration from Settings
            ('reference_loader'|'import_loader')
    """

    options["attach_to_root"] = True
    custom_naming = self.load_settings[loader_key]

    if not custom_naming["namespace"]:
        raise LoadError("No namespace specified in "
                        "Maya ReferenceLoader settings")
    elif not custom_naming["group_name"]:
        self.log.debug("No custom group_name, no group will be created.")
        options["attach_to_root"] = False

    folder_entity = context["folder"]
    product_entity = context["product"]
    product_name = product_entity["name"]
    product_type = product_entity["productType"]
    formatting_data = {
        "asset_name": folder_entity["name"],
        "asset_type": "asset",
        "folder": {
            "name": folder_entity["name"],
        },
        "subset": product_name,
        "product": {
            "name": product_name,
            "type": product_type,
        },
        "family": product_type
    }

    custom_namespace = custom_naming["namespace"].format(
        **formatting_data
    )

    custom_group_name = custom_naming["group_name"].format(
        **formatting_data
    )

    return custom_group_name, custom_namespace, options

MayaHost

Bases: HostBase, IWorkfileHost, ILoadHost, IPublishHost

Source code in client/ayon_maya/api/pipeline.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
class MayaHost(HostBase, IWorkfileHost, ILoadHost, IPublishHost):
    name = "maya"

    def __init__(self):
        super(MayaHost, self).__init__()
        self._op_events = {}

    def install(self):
        project_name = get_current_project_name()
        project_settings = get_project_settings(project_name)
        # process path mapping
        dirmap_processor = MayaDirmap("maya", project_name, project_settings)
        dirmap_processor.process_dirmap()

        pyblish.api.register_plugin_path(PUBLISH_PATH)
        pyblish.api.register_host("mayabatch")
        pyblish.api.register_host("mayapy")
        pyblish.api.register_host("maya")

        register_loader_plugin_path(LOAD_PATH)
        register_creator_plugin_path(CREATE_PATH)
        register_inventory_action_path(INVENTORY_PATH)
        register_workfile_build_plugin_path(WORKFILE_BUILD_PATH)

        self.log.info("Installing callbacks ... ")
        register_event_callback("init", on_init)

        _set_project()

        if lib.IS_HEADLESS:
            self.log.info((
                "Running in headless mode, skipping Maya save/open/new"
                " callback installation.."
            ))

            return

        self._register_callbacks()

        menu.install(project_settings)

        register_event_callback("save", on_save)
        register_event_callback("open", on_open)
        register_event_callback("new", on_new)
        register_event_callback("before.save", on_before_save)
        register_event_callback("after.save", on_after_save)
        register_event_callback("before.close", on_before_close)
        register_event_callback("before.file.open", before_file_open)
        register_event_callback("taskChanged", on_task_changed)
        register_event_callback("workfile.open.before", before_workfile_open)
        register_event_callback("workfile.save.before", before_workfile_save)
        register_event_callback(
            "workfile.save.before", workfile_save_before_xgen
        )
        register_event_callback("workfile.save.after", after_workfile_save)

        self._register_maya_usd_chasers()

    def open_workfile(self, filepath):
        return open_file(filepath)

    def save_workfile(self, filepath=None):
        return save_file(filepath)

    def work_root(self, session):
        return work_root(session)

    def get_current_workfile(self):
        return current_file()

    def workfile_has_unsaved_changes(self):
        return has_unsaved_changes()

    def get_workfile_extensions(self):
        return file_extensions()

    def get_containers(self):
        return ls()

    @contextlib.contextmanager
    def maintained_selection(self):
        with lib.maintained_selection():
            yield

    def get_context_data(self):
        data = cmds.fileInfo("OpenPypeContext", query=True)
        if not data:
            return {}

        data = data[0]  # Maya seems to return a list
        decoded = base64.b64decode(data).decode("utf-8")
        return json.loads(decoded)

    def update_context_data(self, data, changes):
        json_str = json.dumps(data)
        encoded = base64.b64encode(json_str.encode("utf-8"))
        return cmds.fileInfo("OpenPypeContext", encoded)

    def _register_callbacks(self):
        for handler, event in self._op_events.copy().items():
            if event is None:
                continue

            try:
                OpenMaya.MMessage.removeCallback(event)
                self._op_events[handler] = None
            except RuntimeError as exc:
                self.log.info(exc)

        self._op_events[_on_scene_save] = OpenMaya.MSceneMessage.addCallback(
            OpenMaya.MSceneMessage.kBeforeSave, _on_scene_save
        )

        self._op_events[_after_scene_save] = (
            OpenMaya.MSceneMessage.addCallback(
                OpenMaya.MSceneMessage.kAfterSave,
                _after_scene_save
            )
        )

        self._op_events[_before_scene_save] = (
            OpenMaya.MSceneMessage.addCheckCallback(
                OpenMaya.MSceneMessage.kBeforeSaveCheck,
                _before_scene_save
            )
        )

        self._op_events[_on_scene_new] = OpenMaya.MSceneMessage.addCallback(
            OpenMaya.MSceneMessage.kAfterNew, _on_scene_new
        )

        self._op_events[_on_maya_initialized] = (
            OpenMaya.MSceneMessage.addCallback(
                OpenMaya.MSceneMessage.kMayaInitialized,
                _on_maya_initialized
            )
        )

        self._op_events[_on_scene_open] = (
            OpenMaya.MSceneMessage.addCallback(
                OpenMaya.MSceneMessage.kAfterOpen,
                _on_scene_open
            )
        )

        self._op_events[_before_scene_open] = (
            OpenMaya.MSceneMessage.addCallback(
                OpenMaya.MSceneMessage.kBeforeOpen,
                _before_scene_open
            )
        )

        self._op_events[_before_close_maya] = (
            OpenMaya.MSceneMessage.addCallback(
                OpenMaya.MSceneMessage.kMayaExiting,
                _before_close_maya
            )
        )

        self.log.info("Installed event handler _on_scene_save..")
        self.log.info("Installed event handler _before_scene_save..")
        self.log.info("Installed event handler _on_after_save..")
        self.log.info("Installed event handler _on_scene_new..")
        self.log.info("Installed event handler _on_maya_initialized..")
        self.log.info("Installed event handler _on_scene_open..")
        self.log.info("Installed event handler _check_lock_file..")
        self.log.info("Installed event handler _before_close_maya..")

    def _register_maya_usd_chasers(self):
        """Register Maya USD chasers if Maya USD libraries are available."""

        try:
            import mayaUsd.lib  # noqa
        except ImportError:
            # Do not register if Maya USD is not available
            return

        self.log.info("Installing AYON Maya USD chasers..")

        from .chasers import export_filter_properties  # noqa

        for export_chaser in [
            export_filter_properties.FilterPropertiesExportChaser
        ]:
            mayaUsd.lib.ExportChaser.Register(export_chaser,
                                              export_chaser.name)

apply_shaders(relationships, shadernodes, nodes)

Link shadingEngine to the right nodes based on relationship data

Relationship data is constructed of a collection of sets and attributes sets corresponds with the shaderEngines found in the lookdev. Each set has the keys name, members and uuid, the members hold a collection of node information name and uuid.

Parameters:

Name Type Description Default
relationships dict

relationship data

required
shadernodes list

list of nodes of the shading objectSets (includes

required
nodes list

list of nodes to apply shader to

required

Returns:

Type Description

None

Source code in client/ayon_maya/api/lib.py
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
def apply_shaders(relationships, shadernodes, nodes):
    """Link shadingEngine to the right nodes based on relationship data

    Relationship data is constructed of a collection of `sets` and `attributes`
    `sets` corresponds with the shaderEngines found in the lookdev.
    Each set has the keys `name`, `members` and `uuid`, the `members`
    hold a collection of node information `name` and `uuid`.

    Args:
        relationships (dict): relationship data
        shadernodes (list): list of nodes of the shading objectSets (includes
        VRayObjectProperties and shadingEngines)
        nodes (list): list of nodes to apply shader to

    Returns:
        None
    """

    attributes = relationships.get("attributes", [])
    shader_data = relationships.get("relationships", {})

    shading_engines = cmds.ls(shadernodes, type="objectSet", long=True)
    assert shading_engines, "Error in retrieving objectSets from reference"

    # region compute lookup
    nodes_by_id = defaultdict(list)
    for node in nodes:
        nodes_by_id[get_id(node)].append(node)

    shading_engines_by_id = defaultdict(list)
    for shad in shading_engines:
        shading_engines_by_id[get_id(shad)].append(shad)
    # endregion

    # region assign shading engines and other sets
    for data in shader_data.values():
        # collect all unique IDs of the set members
        shader_uuid = data["uuid"]
        member_uuids = [member["uuid"] for member in data["members"]]

        filtered_nodes = list()
        for m_uuid in member_uuids:
            filtered_nodes.extend(nodes_by_id[m_uuid])

        id_shading_engines = shading_engines_by_id[shader_uuid]
        if not id_shading_engines:
            log.error("No shader found with cbId "
                      "'{}'".format(shader_uuid))
            continue
        elif len(id_shading_engines) > 1:
            log.error("Skipping shader assignment. "
                      "More than one shader found with cbId "
                      "'{}'. (found: {})".format(shader_uuid,
                                                 id_shading_engines))
            continue

        if not filtered_nodes:
            log.warning("No nodes found for shading engine "
                        "'{0}'".format(id_shading_engines[0]))
            continue
        try:
            cmds.sets(filtered_nodes, forceElement=id_shading_engines[0])
        except RuntimeError as rte:
            log.error("Error during shader assignment: {}".format(rte))

    # endregion

    apply_attributes(attributes, nodes_by_id)

containerise(name, namespace, nodes, context, loader=None, suffix='CON')

Bundle nodes into an assembly and imprint it with metadata

Containerisation enables a tracking of version, author and origin for loaded assets.

Parameters:

Name Type Description Default
name str

Name of resulting assembly

required
namespace str

Namespace under which to host container

required
nodes list

Long names of nodes to containerise

required
context dict

Asset information

required
loader str

Name of loader used to produce this container.

None
suffix str

Suffix of container, defaults to _CON.

'CON'

Returns:

Name Type Description
container str

Name of container assembly

Source code in client/ayon_maya/api/pipeline.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
@lib.undo_chunk()
def containerise(name,
                 namespace,
                 nodes,
                 context,
                 loader=None,
                 suffix="CON"):
    """Bundle `nodes` into an assembly and imprint it with metadata

    Containerisation enables a tracking of version, author and origin
    for loaded assets.

    Arguments:
        name (str): Name of resulting assembly
        namespace (str): Namespace under which to host container
        nodes (list): Long names of nodes to containerise
        context (dict): Asset information
        loader (str, optional): Name of loader used to produce this container.
        suffix (str, optional): Suffix of container, defaults to `_CON`.

    Returns:
        container (str): Name of container assembly

    """
    container = cmds.sets(nodes, name="%s_%s_%s" % (namespace, name, suffix))

    data = [
        ("schema", "openpype:container-2.0"),
        ("id", AVALON_CONTAINER_ID),
        ("name", name),
        ("namespace", namespace),
        ("loader", loader),
        ("representation", context["representation"]["id"]),
        ("project_name", context["project"]["name"])
    ]
    for key, value in data:
        cmds.addAttr(container, longName=key, dataType="string")
        cmds.setAttr(container + "." + key, str(value), type="string")

    main_container = cmds.ls(AVALON_CONTAINERS, type="objectSet")
    if not main_container:
        main_container = cmds.sets(empty=True, name=AVALON_CONTAINERS)

        # Implement #399: Maya 2019+ hide AVALON_CONTAINERS on creation..
        if cmds.attributeQuery("hiddenInOutliner",
                               node=main_container,
                               exists=True):
            cmds.setAttr(main_container + ".hiddenInOutliner", True)
    else:
        main_container = main_container[0]

    cmds.sets(container, addElement=main_container)

    # Implement #399: Maya 2019+ hide containers in outliner
    if cmds.attributeQuery("hiddenInOutliner",
                           node=container,
                           exists=True):
        cmds.setAttr(container + ".hiddenInOutliner", True)

    return container

ls()

Yields containers from active Maya scene

This is the host-equivalent of api.ls(), but instead of listing assets on disk, it lists assets already loaded in Maya; once loaded they are called 'containers'

Yields:

Type Description

dict[str, Any]: container

Source code in client/ayon_maya/api/pipeline.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def ls():
    """Yields containers from active Maya scene

    This is the host-equivalent of api.ls(), but instead of listing
    assets on disk, it lists assets already loaded in Maya; once loaded
    they are called 'containers'

    Yields:
        dict[str, Any]: container

    """
    container_names = _ls()
    for container in sorted(container_names):
        container_data = parse_container(container)
        if container_data:
            yield container_data

lsattr(attr, value=None)

Return nodes matching key and value

Parameters:

Name Type Description Default
attr str

Name of Maya attribute

required
value object

Value of attribute. If none is provided, return all nodes with this attribute.

None
Example

lsattr("id", "myId") ["myNode"] lsattr("id") ["myNode", "myOtherNode"]

Source code in client/ayon_maya/api/lib.py
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
def lsattr(attr, value=None):
    """Return nodes matching `key` and `value`

    Arguments:
        attr (str): Name of Maya attribute
        value (object, optional): Value of attribute. If none
            is provided, return all nodes with this attribute.

    Example:
        >> lsattr("id", "myId")
        ["myNode"]
        >> lsattr("id")
        ["myNode", "myOtherNode"]

    """

    if value is None:
        return cmds.ls("*.%s" % attr,
                       recursive=True,
                       objectsOnly=True,
                       long=True)
    return lsattrs({attr: value})

lsattrs(attrs)

Return nodes with the given attribute(s).

Parameters:

Name Type Description Default
attrs dict

Name and value pairs of expected matches

required
Example

Return nodes with an age of five.

lsattrs({"age": "five"})

Return nodes with both age and color of five and blue.

lsattrs({"age": "five", "color": "blue"})

Return

list: matching nodes.

Source code in client/ayon_maya/api/lib.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
def lsattrs(attrs):
    """Return nodes with the given attribute(s).

    Arguments:
        attrs (dict): Name and value pairs of expected matches

    Example:
        >>> # Return nodes with an `age` of five.
        >>> lsattrs({"age": "five"})
        >>> # Return nodes with both `age` and `color` of five and blue.
        >>> lsattrs({"age": "five", "color": "blue"})

    Return:
         list: matching nodes.

    """

    dep_fn = OpenMaya.MFnDependencyNode()
    dag_fn = OpenMaya.MFnDagNode()
    selection_list = OpenMaya.MSelectionList()

    first_attr = next(iter(attrs))

    try:
        selection_list.add("*.{0}".format(first_attr),
                           searchChildNamespaces=True)
    except RuntimeError as exc:
        if str(exc).endswith("Object does not exist"):
            return []

    matches = set()
    for i in range(selection_list.length()):
        node = selection_list.getDependNode(i)
        if node.hasFn(OpenMaya.MFn.kDagNode):
            fn_node = dag_fn.setObject(node)
            full_path_names = [path.fullPathName()
                               for path in fn_node.getAllPaths()]
        else:
            fn_node = dep_fn.setObject(node)
            full_path_names = [fn_node.name()]

        for attr in attrs:
            try:
                plug = fn_node.findPlug(attr, True)
                if plug.asString() != attrs[attr]:
                    break
            except RuntimeError:
                break
        else:
            matches.update(full_path_names)

    return list(matches)

maintained_selection()

Maintain selection during context

Example

scene = cmds.file(new=True, force=True) node = cmds.createNode("transform", name="Test") cmds.select("persp") with maintained_selection(): ... cmds.select("Test", replace=True) "Test" in cmds.ls(selection=True) False

Source code in client/ayon_maya/api/lib.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
@contextlib.contextmanager
def maintained_selection():
    """Maintain selection during context

    Example:
        >>> scene = cmds.file(new=True, force=True)
        >>> node = cmds.createNode("transform", name="Test")
        >>> cmds.select("persp")
        >>> with maintained_selection():
        ...     cmds.select("Test", replace=True)
        >>> "Test" in cmds.ls(selection=True)
        False

    """

    previous_selection = cmds.ls(selection=True)
    try:
        yield
    finally:
        if previous_selection:
            cmds.select(previous_selection,
                        replace=True,
                        noExpand=True)
        else:
            cmds.select(clear=True)

read(node)

Return user-defined attributes from node

Source code in client/ayon_maya/api/lib.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
def read(node):
    """Return user-defined attributes from `node`"""

    data = dict()

    for attr in cmds.listAttr(node, userDefined=True) or list():
        try:
            value = cmds.getAttr(node + "." + attr, asString=True)

        except RuntimeError:
            # For Message type attribute or others that have connections,
            # take source node name as value.
            source = cmds.listConnections(node + "." + attr,
                                          source=True,
                                          destination=False)
            source = cmds.ls(source, long=True) or [None]
            value = source[0]

        except ValueError:
            # Some attributes cannot be read directly,
            # such as mesh and color attributes. These
            # are considered non-essential to this
            # particular publishing pipeline.
            value = None

        data[attr] = value

    return data

suspended_refresh(suspend=True)

Suspend viewport refreshes

cmds.ogs(pause=True) is a toggle so we can't pass False.

Source code in client/ayon_maya/api/lib.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
@contextlib.contextmanager
def suspended_refresh(suspend=True):
    """Suspend viewport refreshes

    cmds.ogs(pause=True) is a toggle so we can't pass False.
    """
    if IS_HEADLESS:
        yield
        return

    original_state = cmds.ogs(query=True, pause=True)
    try:
        if suspend and not original_state:
            cmds.ogs(pause=True)
        yield
    finally:
        if suspend and not original_state:
            cmds.ogs(pause=True)

unique_namespace(namespace, format='%02d', prefix='', suffix='')

Return unique namespace

Parameters:

Name Type Description Default
namespace str

Name of namespace to consider

required
format str

Formatting of the given iteration number

'%02d'
suffix str

Only consider namespaces with this suffix.

''

unique_namespace("bar")

bar01

unique_namespace(":hello")

:hello01

unique_namespace("bar:", suffix="_NS")

bar01_NS:

Source code in client/ayon_maya/api/lib.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
def unique_namespace(namespace, format="%02d", prefix="", suffix=""):
    """Return unique namespace

    Arguments:
        namespace (str): Name of namespace to consider
        format (str, optional): Formatting of the given iteration number
        suffix (str, optional): Only consider namespaces with this suffix.

    >>> unique_namespace("bar")
    # bar01
    >>> unique_namespace(":hello")
    # :hello01
    >>> unique_namespace("bar:", suffix="_NS")
    # bar01_NS:

    """

    def current_namespace():
        current = cmds.namespaceInfo(currentNamespace=True,
                                     absoluteName=True)
        # When inside a namespace Maya adds no trailing :
        if not current.endswith(":"):
            current += ":"
        return current

    # Always check against the absolute namespace root
    # There's no clash with :x if we're defining namespace :a:x
    ROOT = ":" if namespace.startswith(":") else current_namespace()

    # Strip trailing `:` tokens since we might want to add a suffix
    start = ":" if namespace.startswith(":") else ""
    end = ":" if namespace.endswith(":") else ""
    namespace = namespace.strip(":")
    if ":" in namespace:
        # Split off any nesting that we don't uniqify anyway.
        parents, namespace = namespace.rsplit(":", 1)
        start += parents + ":"
        ROOT += start

    def exists(n):
        # Check for clash with nodes and namespaces
        fullpath = ROOT + n
        return cmds.objExists(fullpath) or cmds.namespace(exists=fullpath)

    iteration = 1
    while True:
        nr_namespace = namespace + format % iteration
        unique = prefix + nr_namespace + suffix

        if not exists(unique):
            return start + unique + end

        iteration += 1