# Introduction

![image](https://cloud.githubusercontent.com/assets/2152766/6998101/5c13946c-dbcd-11e4-968b-b357b7c60a06.png)

Welcome to the API documentation for Pyblish.

This section contains a listing of available classes, functions and attributes via `pyblish.api`.

```python
>>> import pyblish.api
>>> pyblish.api.discover()
["<class 'collect_current_date.CollectCurrentDate>"]
```

## Introduction

Use this API documentation as reference for specific parts of Pyblish.

**Problem?**

If you encounter a problem with this guide, either..

1. Hover over a paragraph and click the `+` button.
2. Let us know on [the forums](http://forums.pyblish.com).
3. Submit an issue [on GitHub](https://github.com/pyblish/apidocs).
4. Fix it yourself, but submitting [a pull-request](https://github.com/pyblish/apidocs).

## Help fill in the gaps

The content of this book is accurate, but incomplete. You can help add and maintain [this documentation](https://github.com/pyblish/apidocs) via Git and GitHub, or by signing up to the host of this book, [GitBook](https://www.gitbook.com), and volunteering as an editor.

Gain access to the cloud based editor with which to edit pages and make improvements, live.

Find available API members in [`api.py`](https://github.com/pyblish/pyblish-base/blob/master/pyblish/api.py) or by printing it from an interpreter.

```python
import pyblish.api
for member in dir(pyblish.api):
  print(member)
```

{{ file.mtime }}


# Plug-in System

Learn about how things happen in Pyblish.

## Introduction

There are three ways in which a plug-in is associated with a particular set of data.

1. By availability
2. By host
3. By family

Availability is determined by registering a given plug-in to Pyblish, for example by calling [register\_plugin\_path()](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/register_plugin_path.md). Once a plug-in is made available, it must also match the currently running host.

```python
class MyPlugin(...):
  hosts = ["maya"]
```

If the host matches, a plug-in is put to the final test; it's supported families.

```python
class MyPlugin(...):
  families = ["myFamily"]
```

**See also**

* [Plugin.hosts](/pyblish.api/plugin/plugin.hosts)

## Data

These data members are included.

| Data         | Description                                       |
| ------------ | ------------------------------------------------- |
| currentFile  | Current working file                              |
| workspaceDir | Higher-level directory of current file            |
| user         | Currently logged on user                          |
| cwd          | Current working directory (of Python interpreter) |

**Example**

```python
import pyblish.util
context = pyblish.util.collect()
print context.data["currentFile"]
```

\[2]: <https://github.com/pyblish/pyblish.api/wiki/Plugin.hosts>


# Data


# result

The `result` dictionary is produced once per process and contains information about what happened, primarily intended for use in graphical user interfaces.

## Overview

These members are available in each result produced.

```javascript
{
    success: "Status of processing."
    instance: "Name of processed instance or null if no instance were processed."
    plugin: "Instance of current plug-in at the time."
    duration: "Time in milliseconds taken to process a pair."
    error: "Instance of exception thrown (if any)."
    records: "List of log messages made."
}
```

## Example

```python
import pyblish.util
context = pyblish.util.publish()

for result in context.data["results"]:
  print("Success!" if result["success"] else "Failed..")

  # All log messages are captured in `records`
  for record in result["records"]:
    print(record)
```

## Full schema

* [result.json](https://github.com/pyblish/pyblish-qml/blob/master/pyblish_qml/ipc/schema/result.json)
* [All schemas](https://github.com/pyblish/pyblish-qml/blob/master/pyblish_qml/ipc/schema)

**Snapshot from** [**1a350**](https://github.com/pyblish/pyblish-qml/blob/1a35024c7aeccae858146cce62202d2b43b8c826/pyblish_qml/ipc/schema/result.json)

```javascript
{
    "$schema": "http://json-schema.org/schema#",

    "title": "Result",
    "description": "Result from processing a (plugin, instance) pair",

    "type": "object",

    "additionalProperties": false,

    "properties": {
        "success": {
            "description": "Status of processing",
            "type": "boolean"
        },
        "instance": {
            "description": "Name of processed instance or null if no instance were processed",
            "oneOf": [
                {"$ref": "instance.json"},
                {"type": "null"}
            ]
        },
        "plugin": {
            "oneOf": [
                {"$ref": "plugin.json"},
                {"type": "null"}
            ]
        },
        "duration": {
            "description": "Time in milliseconds taken to process a pair",
            "type": "number"
        },
        "error": {
            "oneOf": [
                {"$ref": "error.json"},
                {"type": "null"}
            ]
        },
        "records": {
            "type": "array",
            "items": {
                "$ref": "record.json"
            }
        }
    },

    "definitions": {}
}
```

{{ file.mtime }}


# Events

This is a listing of default events in Pyblish.

**Pyblish**

| Event             | Arguments                                | Description                                          |
| ----------------- | ---------------------------------------- | ---------------------------------------------------- |
| `published`       | `context`                                | Emitted upon finished publish, regardless of failure |
| `validated`       | `context`                                | Emitted upon finished validation                     |
| `pluginFailed`    | `plugin`, `context`, `instance`, `error` | Emitted once per failed plug-in.                     |
| `pluginProcessed` | `result`                                 | Emitted once per processed plug-in.                  |

**Pyblish QML**

| Event             | Arguments                        | Description                           |
| ----------------- | -------------------------------- | ------------------------------------- |
| `instanceToggled` | `instance, new_value, old_value` | An Instance was toggled in the GUI    |
| `pluginToggled`   | `plugin, new_value, old_value`   | A Plug-in was toggled in the GUI      |
| `pyblishQmlShown` |                                  | When the Pyblish QML window is shown. |

## Examples

Print status once publishing has finished.

```python
import pyblish.api

def on_published(context):
  has_error = any(result["error"] is not None for result in context.data["results"])
  print("Publishing %s" % ("finished" if has_error else "failed"))

pyblish.api.register_callback("published", on_published)
```

Print in the event of a user toggling an instance in a GUI.

```python
import pyblish.api

def on_instance_toggled(instance, new_value, old_value):
  print("%s was toggled from %s to %s" % (instance, new_value, old_value))

pyblish.api.register_callback("instanceToggled", on_instance_toggled)
```

{{ file.mtime }}


# Targets

Filter plug-ins by an arbitrary "target", such as `Global Assets`, `Local User`, `Animators`, `Everyone with Read Hair` etc.

This differs from `families` in that the caller provides the data, as opposed to the DCC. Useful for special-purpose GUIs or publishing tasks.

## Targets Workflow

This release enables assigning targets to plugins. Targets are registered globally so you can enable and disable plugins based on targets. This workflow helps when needing to run plugins from the same host but with different sets of plugins. Possible use cases could be submitting to a render farm, or publishing to a different location.

Targets work the same way as families, so a wildcard of `*` enables the plugin for all targets. Since all plugins are registered with `*` as targets, this workflow is backwards compatible with existing plugins that has not overwritten the targets attribute.

**Targets with `publish.util`**

```python
from pyblish import api, util


class plugin(api.ContextPlugin):
targets = ["custom"]

def process(self, context):
self.log.info("Custom target publishing.")


api.register_plugin(plugin)

util.publish(targets=["custom"])
```

### Example

```python
import pyblish.api
import pyblish.util

class StudioPlugin(pyblish.api.ContextPlugin):

    targets = ["studio"]

    def process(self, context):
        self.log.info("Publishing to studio library.")

class ProjectPlugin(pyblish.api.ContextPlugin):

    def process(self, context):
        self.log.info("Publishing to project library.")


pyblish.api.register_plugin(StudioPlugin)
pyblish.api.register_plugin(ProjectPlugin)

# Publishing with ProjectPlugin only.
pyblish.util.publish()

# Publishing with ProjectPlugin and StudioPlugin.
pyblish.api.register_target("studio")
pyblish.util.publish()
```

{{ file.mtime }}


# Environment Variables


# PYBLISHPLUGINPATH

One or more paths from which to discover Pyblish plug-ins.

## Usage

The environment variable is typically set prior to launching an application, such that the given application can be tailored for a given task or project, and then have access to these plug-ins at run-time.

## Example

```python
import os
os.environ["PYBLISHPLUGINPATH"] = r"c:\pyblish_plugins"
os.environ["PYBLISHPLUGINPATH"] = "/home/pyblish_plugins"
```

{{ file.mtime }}


# PYBLISH\_CLIENT\_PORT

This contains the currently used port number to communicate with [pyblish-qml](https://github.com/pyblish/pyblish-qml).

## Usage

You typically won't have to use this, but can be helpful during debugging sessions. It is written upon starting the server but never read, so changing it will not have any effect.

## Example

From [Communicating with the host](https://pyblish.gitbooks.io/developer-guide/content/communicating_with_the_host.html) in the Developer Guide.

```python
import os
import xmlrpclib
proxy = xmlrpclib.ServerProxy("http://127.0.0.1:9001/pyblish")
proxy.discover()
# {...}
```

{{ file.mtime }}


# PYBLISH\_ALLOW\_DUPLICATE\_PLUGINS

Allow duplicate plugin names to load.

## Usage

Normal behaviour will discard any plugin with the same name, as a previously loaded plugin.

## Example

```python
import os
os.environ["PYBLISH_ALLOW_DUPLICATE_PLUGINS"] = "True"
```

{{ file.mtime }}


# PYBLISH\_GUI

Set which GUI to register and load.

## Usage

Setting this environment variable will enable Pyblish to register and load a GUI.

## Example

```python
import os
os.environ["PYBLISH_GUI"] = "pyblish_qml"
```

{{ file.mtime }}


# PYBLISH\_EARLY\_ADOPTER

Enable all new backwards incompatible changes.

## Usage

Backwards incompatible changes:

* <https://github.com/pyblish/pyblish-base/pull/332>
* <https://github.com/pyblish/pyblish-base/pull/324>

## Example

```python
import os
os.environ["PYBLISH_EARLY_ADOPTER"] = "True"
```

{{ file.mtime }}


# PYBLISH\_STRICT\_DATATYPES

Throw errors when assigning invalid data types.

## Usage

When enabled the values in both `instance.data` and `context.data` will be validated.

```python
data = {
  "publish": True  # Boolean for GUIs to function.
}
```

## Example

```python
import os
os.environ["PYBLISH_STRICT_DATATYPES"] = "True"
```

{{ file.mtime }}


# Ordering


# CollectorOrder

Collectors create [instances](/pyblish.api/instance).

## Example

```python
import os
import pyblish.api as pyblish

class MyCollector(pyblish.ContextPlugin):
    """This plug-in identifies content and creates instances"""

    order = pyblish.CollectorOrder

    def process(self, context):
        for folder in os.listdir("."):
            if not folder.endswith("_asset"):
                continue
            instance = context.create_instance(folder)
            instance.data["family"] = "asset"
```

{{ file.mtime }}


# ValidatorOrder

A validator determines whether or not an [instance](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/instance.md) is valid.

**Illustration**

```
  _______                                  _____
         |                                |
input    |------ is valid? ----- yes ---->|  output
  _______|           |                    |_____
     ^               |
     |               no
     |               |
     |_______________|
```

## Example

```python
import pyblish.api as pyblish

class MyValidator(pyblish.InstancePlugin):
    """Documentation goes here"""

    order = pyblish.ValidatorOrder

    def process(self, instance):
        self.log.info("something")
```

{{ file.mtime }}


# ExtractorOrder

An extractor writes [instances](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/instance.md) to disk.

## Example

```python
import pyblish.api as pyblish

class MyExtractor(pyblish.InstancePlugin):
    """Extract to disk"""

    order = pyblish.ExtractorOrder

    def process(self, instance):
        ...
```

{{ file.mtime }}


# IntegratorOrder

A integrator integrates [instances](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/instance.md) with a pipeline.

## Example

```python
import pyblish.api as pyblish

class MyIntegrator(pyblish.InstancePlugin):
    """Integrate to disk"""

    order = pyblish.IntegratorOrder

    def process(self, instance):
        import shutil
        shutil.copytree(
            src=instance.data["sourceDir"],
            dst="/server/{name}/{fname}".format(
                **instance.data)
        )
```

{{ file.mtime }}


# pyblish.util


# publish

Publish via Python.

| Source                                                                                          | Added  |
| ----------------------------------------------------------------------------------------------- | ------ |
| [Link](https://github.com/pyblish/pyblish-base/commit/68ded825ea07b6de3bd5a791628815a9394d6156) | 1.0.16 |

## Description

This function runs all currently discoverable plug-ins and is especially useful when running without a GUI or to run remotely.

## Argument Signature

|                          Output | Method                                                                             |
| ------------------------------: | ---------------------------------------------------------------------------------- |
| [Context](/pyblish.api/context) | publish([context](/pyblish.api/context)=None, [plugins](/pyblish.api/plugin)=None) |

## Example

```python
import pyblish.util
context = pyblish.util.publish()
```

{{ file.mtime }}


# collect

Run collection via Python.

| Source                                                                                          | Added  |
| ----------------------------------------------------------------------------------------------- | ------ |
| [Link](https://github.com/pyblish/pyblish-base/commit/68ded825ea07b6de3bd5a791628815a9394d6156) | 1.0.16 |

## Description

This function runs plug-ins of [CollectionOrder](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/CollectionOrder.md) and then stops. This is useful for getting hold of a populated [Context](/pyblish.api/context)

## Argument Signature

|                          Output | Method                                                                             |
| ------------------------------: | ---------------------------------------------------------------------------------- |
| [Context](/pyblish.api/context) | collect([context](/pyblish.api/context)=None, [plugins](/pyblish.api/plugin)=None) |

## Example

```python
import pyblish.util
context = pyblish.util.collect()
```

{{ file.mtime }}


# validate

Run validation-only via Python.

| Source                                                                                          | Added  |
| ----------------------------------------------------------------------------------------------- | ------ |
| [Link](https://github.com/pyblish/pyblish-base/commit/68ded825ea07b6de3bd5a791628815a9394d6156) | 1.0.16 |

## Description

This function runs plug-ins of [ValidationOrder](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/ValidationOrder.md) and then stops. This is useful for getting hold of a validated [Context](/pyblish.api/context) with [results](/data/result).

## Argument Signature

|                          Output | Method                                                                              |
| ------------------------------: | ----------------------------------------------------------------------------------- |
| [Context](/pyblish.api/context) | validate([context](/pyblish.api/context)=None, [plugins](/pyblish.api/plugin)=None) |

## Example

```python
import pyblish.util
context = pyblish.util.collect()
pyblish.util.validate(context)
```

{{ file.mtime }}


# extract

Run extraction-only via Python.

| Source                                                                                          | Added  |
| ----------------------------------------------------------------------------------------------- | ------ |
| [Link](https://github.com/pyblish/pyblish-base/commit/68ded825ea07b6de3bd5a791628815a9394d6156) | 1.0.16 |

## Description

This function runs plug-ins of [ExtractionOrder](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/ExtractionOrder.md) and then stops. This is useful for getting hold of an extracted [Context](/pyblish.api/context), bypassing validation, with [results](/data/result).

## Argument Signature

|                          Output | Method                                                                             |
| ------------------------------: | ---------------------------------------------------------------------------------- |
| [Context](/pyblish.api/context) | extract([context](/pyblish.api/context)=None, [plugins](/pyblish.api/plugin)=None) |

## Example

```python
import pyblish.util
context = pyblish.util.collect()
pyblish.util.extract(context)
```

{{ file.mtime }}


# integrate

Run integration-only via Python.

| Source                                                                                          | Added  |
| ----------------------------------------------------------------------------------------------- | ------ |
| [Link](https://github.com/pyblish/pyblish-base/commit/68ded825ea07b6de3bd5a791628815a9394d6156) | 1.0.16 |

## Description

This function runs plug-ins of [IntegrationOrder](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/IntegrationOrder.md) and then stops. This is useful for getting hold of an integrated [Context](/pyblish.api/context), bypassing validation and extraction, with [results](/data/result).

## Argument Signature

|                          Output | Method                                                                               |
| ------------------------------: | ------------------------------------------------------------------------------------ |
| [Context](/pyblish.api/context) | integrate([context](/pyblish.api/context)=None, [plugins](/pyblish.api/plugin)=None) |

## Example

```python
import pyblish.util
context = pyblish.util.collect()
pyblish.util.integrate(context)
```

{{ file.mtime }}


# pyblish.cli


# publish

The Pyblish command-line interface can be accessed via `python -m pyblish`, or directly via `pyblish` when installed via `pip`.

You can use this interface to trigger publishes via the command-line.

```bash
$ pip install pyblish
$ pyblish --help
Usage: pyblish [OPTIONS] COMMAND [ARGS]...

  Pyblish command-line interface

  Use the appropriate sub-command to initiate a publish.

  Use the --help flag of each subcommand to learn more about what it can do.

  Usage:
      $ pyblish publish --help
      $ pyblish test --help

Options:
  --verbose                       Display detailed information. Useful for
                                  debugging purposes.
  --version                       Print the current version of Pyblish
  --paths                         List all available paths
  --plugins                       List all available plugins
  --registered-paths              Print only registered-paths
  --environment-paths             Print only paths added via environment
  -pp, --plugin-path TEXT         Replace all normally discovered paths with
                                  this This may be called multiple times.
  -ap, --add-plugin-path TEXT     Append to normally discovered paths.
  -d, --data TEXT...              Initialise context with data. This takes two
                                  arguments, key and value.
  -ll, --logging-level [debug|info|warning|critical|error]
                                  Specify with which level to produce logging
                                  messages. A value lower than the default
                                  "warning" will produce more messages. This
                                  can be useful for debugging.
  --help                          Show this message and exit.

Commands:
  publish  Publish instances of path.
```

{{ file.mtime }}


# pyblish.api


# AbstractEntity

Abstract base-class to [Instance](/pyblish.api/instance) and [Context](/pyblish.api/context).

| Source                                                                                                          | Added |
| --------------------------------------------------------------------------------------------------------------- | ----- |
| [Link](https://github.com/pyblish/pyblish/blob/6e9bfce6254ea56411af857afa49423a57f7b425/pyblish/plugin.py#L466) | 0.1.6 |

Inherits [list](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists).

## Properties

| Output | Property                                                 |
| -----: | -------------------------------------------------------- |
|   dict | [.data](/pyblish.api/abstractentity/abstractentity.data) |

{{ file.mtime }}


# .data

Available to [Instance](/pyblish.api/instance) and [Context](/pyblish.api/context) objects and used to pass data between library and plug-ins.

## Introduction

Data is primarily gathered during [Collection](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/Collector.md) and used during subsequent plug-ins, such as [Validation](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/Validator.md) and [Extraction](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/Extractor.md). Data can also be used as a means of messaging across plug-ins.

* See [Tale of Three APIs](https://github.com/pyblish/pyblish/wiki/Tale-of-Three-APIs) for more information.

## Naming Convention

Data members are using mixedCase.

**Wrong**

```bash
instance.data["snake_case_is_for_python"] = True
instance.data["CamelCaseIsForClasses"] = False
```

**Right**

```bash
instance.data["myVariable"] = True
instance.data["longName"] = 42
instance.data["veryLongVariable"] = 5
```

The motivation is to separate between what is Python and what is Pyblish data.

## Examples

```python
import pyblish.api as pyblish
context = pyblish.Context()
context.data["myData"] = "myValue"

instance = pyblish.Instance(name="MyInstance", parent=context)
instance.data["range"] = [0, 120]
instance.data["active"] = False
```

Data of any type may be added, including complex objects.

```python
# Custom objects

import pyblish.api

class MyCustomChild(object):
   def __init__(self, name):
      self.name = name

instance = pyblish.api.Instance(name="Car")
instance.append(MyCustomChild("wheels"))
instance.append(MyCustomChild("engine"))

MyCustomType = type("MyCustomType", (object,), {})

owner = MyCustomType()
owner.value = "John Doe"
make = MyCustomType()
make.value = "Ford"

instance.data["owner"] = owner
instance.data["make"] = make
instance.data["miles"] = "123"
```

{{ file.mtime }}


# Context

The context represents the world.

| Source                                                                                                          | Added |
| --------------------------------------------------------------------------------------------------------------- | ----- |
| [Link](https://github.com/pyblish/pyblish/blob/6e9bfce6254ea56411af857afa49423a57f7b425/pyblish/plugin.py#L542) | 0.1.6 |

Inherits [AbstractEntity](/pyblish.api/abstractentity)

## Public Functions

|   Output | Method                                                                             |
| -------: | ---------------------------------------------------------------------------------- |
| Instance | [.create\_instance](/pyblish.api/context/context.create_instance)(str, \*\*kwargs) |

4 functions inherited from [AbstractEntity](/pyblish.api/abstractentity)

## Description

The context encapsulates one or more [Instance](/pyblish.api/instance)'s along with information about the current execution environment, such as the current user and time of day. Publishing is performed by iterating over the members of a context.

```python
# Psuedo-code
for plugin in plugins:
  for instance in context:
     plugin.process(instance)
```

## Examples

```python
# Creating a context
#
# The context is normally created for you by a user interface or
# through convenience functions, but can be helpful to manually
# create for debugging purposes.

import pyblish.api as pyblish
context = pyblish.Context()
```

```python
# Creating instances from a context
#
# Instances can be created directly or through a context. When
# created through a context, the context is automatically set
# as the parent of the newly created instance.

import pyblish.api as pyblish
context = pyblish.Context()
instanceA = context.create_instance(name="MyInstanceA")
instanceB = pyblish.Instance(name="MyInstanceB", parent=context)

print("The context contains these instances:")
for instance in context:
    print(instance)
# MyInstanceA
# MyInstanceB
```

```python
# Setting data on a context
# 
# Both Instance and Context inherit from AbstractEntity which
# provides the mechanism for modifying data.

import pyblish.api as pyblish
context = pyblish.Context()
data = context.data
context.data["hostname"] = "localhost"
assert "hostname" in context.data is True
context.data.pop("hostname")
assert "hostname" in context.data is False
```

{{ file.mtime }}


# .append

Append [Instances](/pyblish.api/instance) to a [Context](/pyblish.api/context).

## Introduction

A context may contain both content and metacontent, added via `.append()` and `.data[]` respectively.

The contents of a Context is the instances, and it's data global information about the environment in which publishing occurs, such as time of day or currently logged on user.

## Examples

```python
import pyblish.api as pyblish

context = pyblish.Context()
instance = pyblish.Instance(name="MyInstance")
context.append(instance)
```

{{ file.mtime }}


# .create\_instance

Create [Instances](/pyblish.api/instance) for a given [Context](/pyblish.api/context).

## Introduction

Create an instance and automatically make it a child of the calling context, returns the newly created [Instance](/pyblish.api/instance).

```python
import pyblish.api
context = pyblish.api.Context()
instance = context.create_instance(name="MyInstance")
```

{{ file.mtime }}


# Instance

An instance is a *unit* of data.

| Source                                                                                                          | Added |
| --------------------------------------------------------------------------------------------------------------- | ----- |
| [Link](https://github.com/pyblish/pyblish/blob/6e9bfce6254ea56411af857afa49423a57f7b425/pyblish/plugin.py#L572) | 0.1.6 |

Inherits [AbstractEntity](/pyblish.api/abstractentity)

## Properties

|                          Output | Property                                          |
| ------------------------------: | ------------------------------------------------- |
| [Context](/pyblish.api/context) | [context](/pyblish.api/instance/instance.context) |

## Public Functions

| Output | Method                                                                                                                  |
| -----: | ----------------------------------------------------------------------------------------------------------------------- |
|        | [append](/pyblish.api/instance/instance.append)(object)                                                                 |
|        | [remove](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/Instance.remove.md)(object) |

4 functions inherited from [AbstractEntity](/pyblish.api/abstractentity)

## Description

Instances are a core component of Pyblish. To get a sense of what they are, think of **instances** as the inverse of **files**; i.e. when you load a file into an application, you get an *instance* of that file.

Thus, when constructing an `Instance`, simply ask yourself:

* *"What am I looking to store on disk?"*

## Content and Metacontent

An instance may contain both *content* and *metacontent*.

You can think of the contents of an instance like how bytes are the contents of a file, whereas metacontent represents additional information about an instance, such as author and time last modified.

```
 Instance
 _______________________________
|  content         metacontent  |
|  __   __         _        _   |
| |       |       /          \  |
| | child |      | key: value | |
| | child |      < key: value > |
| | child |      | key: value | |
| |__   __|       \_        _/  |
|______________________________ |

  .append(child)    .data[key] = value
```

## Examples

```python
import pyblish.api

instance = pyblish.api.Instance(name="MyInstance")
instance.data["name"] = "My instance."
instance.append("NodeName1")
instance.append(custom_object)
```

```python
# Creating an instance from a context automatically
# makes it a child of that context.

import pyblish.api

context = pyblish.api.Context()
instance_a = pyblish.api.Instance(name="MyInstanceA", parent=context)
instance_b = context.create_instance(name="MyInstanceB")
```

## Origin

The word "instance" generally refers to "an occurence" of something. This *something* may occur multiple times, but it still refers to the same *something*.

Let's take an example.

```python
# Copy & Paste                     |            # Hard Link
 _______        _______            |             _______        _______   
|      |\      |      |\           |            |      |\      |      |\  
|       |      |       |           |            |       |      |       |  
|   A   |      |   B   |           |            |   A   |      |   B   |  
|       |      |       |           |            |       |      |       |  
|_______|      |_______|           |            |_______|      |_______|  
    |              |               |                 \           /
    |              |               |                  \         / 
 ___|___        ___|___            |                   \_______/
|       |      |       |           |                   |       |
|   A   |      |   B   |           |                   |   A   |
|_______|      |_______|           |                   |_______|
```

Each file on your file-system refers to data in your disk. If you copy a file and paste it somewhere else, you end up with two files that refer to *two different sets of data*. This is because the copy you made of the file is also made of the data on disk.

You can confirm this by keeping an eye on the disk usage before and after you make the copy. It increases.

On the other hand, if you create what is known as a "hard link" to this file, you will also end up with two files. But this time, the two different files will refer to *the same set of data*.

Thus, no matter how many hard links you make, you will never spend any more disk space that what is required to store the handle to the file (a few bytes at most).

In Pyblish, this concept is very much the same.

In fact, you can think of an `Instance` as the *inverse* of a file. When loading a file into an application, what you end up with is the *instance* of that file. No matter how many times you load the file, each *instance* will refer to the same file on disk.

* [Hard link](http://en.wikipedia.org/wiki/Hard_link)


# .append

Append *content* to an [Instance](/pyblish.api/instance).

## Introduction

The content of an [Instance](/pyblish.api/instance) is a reflection of the content in the resulting file(s) on disk.

An instance may contain both content and metacontent, added via `.append()` and `.data[]` respectively. You can think of the contents of an instance as the bytes for a file, whereas metacontent represents additional information about an instance, such as author and date modified.

When used within a host, the content typically refers to the part of a workspace that is to be published, such as a the physical nodes making up a character model or rig.

## Examples

```python
import pyblish.api

instance = pyblish.api.Instance(name="Car")
instance.append("wheels")
instance.append("engine")
instance[:] = ["wheels", "engine"]
instance[0] = "feet"
```


# .context

Reference to parent [Context](/pyblish.api/context).

## Examples

```python
context = instance.context
context.data["user"] = "Marcus"
```


# Plugin

Plug-ins are snippets of code, discovered at run-time and defines the behaviour of Pyblish.

| Source                                                                                                          | Added |
| --------------------------------------------------------------------------------------------------------------- | ----- |
| [Link](https://github.com/pyblish/pyblish/blob/6e9bfce6254ea56411af857afa49423a57f7b425/pyblish/plugin.py#L119) | 0.1.6 |

## Properties

| property                                        | type  |
| ----------------------------------------------- | ----- |
| [hosts](/pyblish.api/plugin/plugin.hosts)       | list  |
| [families](/pyblish.api/plugin/plugin.families) | list  |
| [label](/pyblish.api/plugin/plugin.label)       | str   |
| [active](/pyblish.api/plugin/plugin.active)     | bool  |
| [version](/pyblish.api/plugin/plugin.version)   | tuple |
| [actions](/pyblish.api/plugin/plugin.actions)   | list  |
| [order](/pyblish.api/plugin/plugin.order)       | float |
| [optional](/pyblish.api/plugin/plugin.optional) | bool  |
| [requires](/pyblish.api/plugin/plugin.requires) | str   |
| [match](/pyblish.api/plugin/plugin.match)       | int   |


# .hosts

Supported hosts.

## Introduction

Read about the architecture of plug-ins for a better understanding of the `hosts` attribute.

* [Plug-in System](https://github.com/pyblish/pyblish/wiki/Plugin-system)

## Example

Each integration provides support for a given host, for detailed information about plug-ins in a particular host, see its corresponding documentation.

```python
class MyPlugin(...):
   hosts = ["maya"]
```


# .families

Supported families.

## Introduction

Read about the architecture of plug-ins for a better understanding of the `families` attribute.

## Implementation

A plug-in may support one or more families by appending it's absolute name to the `families` attribute.

```python
class MyPlugin(...):
   families = ["myFamily"]
```


# .label

Provide an alternative, human-readable name of a plug-in.

## Introduction

Graphical user interfaces use the label as an alternative name for better readability. For example, you can use spaces and preserve case of a label.

## Example

```python
import pyblish.api

class MyCollector(pyblish.api.ContextPlugin):
    label = "My Collector"
```

{{ file.mtime }}


# .active

A hint about whether or not to trigger the plug-in.

## Introduction

This attribute provides the Pyblish run-time with hint meaning "don't run". Under normal circumstances, a plugin with `active = False` is not processed.

## Example

```python
import pyblish.api

class MyCollector(pyblish.api.ContextPlugin):
    active = False
```

{{ file.mtime }}


# .order

Control the order of execution.

## Introduction

Plug-ins are sorted by this attribute. By altering the order of a subclass, you effectively have control over the order in which a particular plug-in is set to execute.

```yaml
# Default order per plug-in superclass
Selector: 0
Validator: 1
Extractor: 2
Conform: 3
```

Sorting is performed via the [sort](/pyblish.api/sort) function and works similar to this.

```python
plugins.sort(key=lambda p: p.order)
```

## Usage

By incrementing the order, you can offset how they are sorted and executed.

```python
class ValidateAfter(pyblish.api.InstancePlugin):
   order = 1.5
```

As the default order for a [Validator](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/Validator.md) is `1`, setting it to `1.5` means that this particular subclass will run once all validators still at the default order have finished.

To protect yourself against changes to the inherited order, it is recommended that you *offset* the order as opposed to setting it to an absolute value.

```python
class ValidateFirst(pyblish.api.InstancePlugin):
   order = pyblish.api.ValidatorOrder + 0.5
```

**Example**

Here's an example of three plug-ins of the same superclass, set to run one after the other.

```python
class ValidateFirst(pyblish.api.InstancePlugin):
   order = pyblish.api.ValidatorOrder + 0

class ValidateSecond(pyblish.api.InstancePlugin):
   order = pyblish.api.ValidatorOrder + 0.1

class ValidateThird(pyblish.api.InstancePlugin):
   order = pyblish.api.ValidatorOrder + 0.2
```

## Behavior

Each order have a special meaning to Pyblish.

> 0-1

Implies [Collector](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/Collector.md). It is run first, sometimes automatically, such as when launching the Pyblish QML graphical user interface.

> 1-2

Implies [Validation](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/validator.md).

> 2-3

Implies [Extraction](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/Extractor.md). It *does not* run if any plug-in within range `1-2` has produced an error.

> 3+

Implies [Integration](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/Integration.md). Like [Extraction](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/Extractor.md), it only runs if validation was successful.

## Caution

Keep in mind that if you offset an order too far, you effectively alter it's role in the Pyblish ecosystem which may cause undefined behaviour.

```python
class ValidateSecond(pyblish.api.InstancePlugin):
   # When does this plug-in run?
   order = 6
```

If you find yourself working with a large number of interdependent plug-ins, it is recommended that you subclass the super-classes and make ordering explicit.

**pipeline/pyblish.py**

```python
import pyblish.api as pyblish

class DefaultValidator(pyblish.InstancePlugin):
     order = pyblish.ValidatorOrder

class PreValidator(pyblish.InstancePlugin):
     order = pyblish.ValidatorOrder - 0.1

class PostValidator(pyblish.InstancePlugin):
     order = pyblish.ValidatorOrder + 0.1
```

You can then replace the provided classes with your with your own.

**/my\_plugins/validate\_something.py**

```python
import pipeline.pyblish

class ValidateSomething(pipeline.pyblish.PostValidator):
    ...
```


# .optional

Optional hint.

## Description

This attribute is primarily intended for user interfaces where a user is given a choice about whether or not to trigger a plug-in.


# .requires

Specify plug-in dependencies.

## Description

This attribute is used during the discovery of plug-ins to determine whether they are compatible with the given environment. For example, a plug-in may specify a value of `pyblish>=1.1` meaning it will only work with Pyblish 1.1 and above.

For syntax reference, see [iscompatible](https://github.com/mottosso/iscompatible).


# .actions

Associate [actions](/pyblish.api/action) with a plug-in.

| Source                                                                                                               | Added |
| -------------------------------------------------------------------------------------------------------------------- | ----- |
| [Link](https://github.com/pyblish/pyblish-base/blob/ac83f2a94bbde95bc2f6c4000d7c50e36a3d3b5f/pyblish/plugin.py#L346) | 1.2.0 |

## Example

```python
import pyblish.api

class MyAction(pyblish.api.Action):
    def process(self, context, plugin):
        self.log.info("I'm an action")

class MyCollector(pyblish.api.ContextPlugin):
    actions = [MyAction]
```

{{ file.mtime }}


# .version

Plug-in version.

## Description

This attribute, containing a semantic version in the form of a tuple, is used in to determine which out of multiple plug-ins of identical names are to be used.

For example, it assumes `MyPlugin.version == (1.0.0)` to be newer than `MyPlugin.version == (0.9.0)` and is therefore favoured, whereas the older version is discarded.


# .match

Control how families are matched amongst plug-ins and instances.

| Source                                                                                                               | Added                                                               |
| -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| [Link](https://github.com/pyblish/pyblish-base/blob/6dc5781d6bb7b97fb7bc9df268f59e24a477c272/pyblish/plugin.py#L238) | [1.4.3](https://github.com/pyblish/pyblish-base/releases/tag/1.4.3) |

## Introduction

The way instances are associated with plug-ins are via their `families`.

Instances and plug-ins may support one or more families, and instances matching one or more of these families are said to be associated with it.

An instance may be associated via a plug-in in 1 of 3 ways.

1. Intersection
2. Subset
3. Exact

By default, an instance of any family within the supported families of a plug-in is a match. This is called **Intersection** and stems from basic set theory.

```python
assert set(["a", "b"]).intersection(["b", "c"])
```

This is useful in the most general case, of one plug-in supporting many different - possibly unrelated - families. Such as one plug-in supporting both models and rigs, say for an established naming convention across both families.

**Subset** on the other hand means the families of an Instance must be a *subset* of the supported families of any plug-in.

Again the concept is borrowed from set theory.

```python
assert set(["a", "b"]).issubset(["a", "b", "c"])
```

This can be useful when instances are specialised, such as being a `lowpoly` family of a `model`, or `animation` family of a `rig`.

Finally, there is **Exact** which captures edge-cases or otherwise highly context sensitive instances, such as an `animation` `rig` in `shot05`.

The algorithm is as follows.

```python
assert set(["a", "b"]) == set(["b", "a"])
```

## Usage

Decide whether your plug-in targets many unrelated families, or specialises in a few, then associate an algorithm with this plug-in.

**Example**

In this example, `SpecificPlugin` is associated to instances whose family(ies) are a **subset** of the supported families model and low. If the instance does not have at least both of these, it is not a match.

This is different from `GenericPlugin`, where only one of the families of an instance need to match any of the supported families of a plug-in. This is called **intersection**.

```python
from pyblish import api

class GenericPlugin(api.InstancePlugin):
  # Support both models and rigs
  families = ["model", "rig"]

  def process(self, instance):
    # Applies to both models and rigs
    assert "parent_GRP" in instance

class SpecificPlugin(api.InstancePlugin):
  # Support models, but only low-poly models
  families = ["model", "low"]
  match = api.Subset

  def process(self, instance):
    # Safe to assume it has a `polyCount` due
    # to only capturing models.
    assert instance.data["polyCount"] < 500
```

The last possible value is `Exact` which means an instance only matches when families of both instance and plug-ins match exactly.

```python
class EdgeCasePlugin(api.InstancePlugin):
  families = ["model", "low", "level21"]
  match = api.Exact

  def process(self, instance):
    assert "specialMember" in instance
```


# ContextPlugin

Process once, with [Context](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/context.md) as input.

| Source                                                                                                               | Added |
| -------------------------------------------------------------------------------------------------------------------- | ----- |
| [Link](https://github.com/pyblish/pyblish-base/blob/f695fad94b995915495b4123c503f24d3419429a/pyblish/plugin.py#L350) | 1.3.0 |

Inherits [Plugin](/pyblish.api/plugin)

## Public Functions

| Output | Method                                                                                       |
| -----: | -------------------------------------------------------------------------------------------- |
|        | [process](/pyblish.api/contextplugin/contextplugin.process)([context](/pyblish.api/context)) |

## Usage

The `ContextPlugin` is used for processing an entire scene or workspace. It is typically used during the collection portion of publishing, where data is identified and encapsulated in one or more [Instances](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/instance.md), but can in general be used for any processing that doesn't require access to any particular [Instance](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/instance.md).

## Example

```python
import pyblish.api as pyblish

class MyCollector(pyblish.ContextPlugin):
    order = pyblish.CollectorOrder

    def process(self, context):
        context.create_instance("MyInstance")
```


# .process

## ContextPlugin.process

The primary processing mechanism of the [Context](/pyblish.api/context).

### Introduction

This method may be overridden in your plug-in subclasses to process the current [Context](/pyblish.api/context).

## Example

```python
import pyblish.api

class CollectInstances(pyblish.api.ContextPlugin):
    order = pyblish.api.CollectorOrder

    def process(self, context):
        context.create_instance("MyInstance")
```


# InstancePlugin

Process once per [Instance](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/instance.md).

| Source                                                                                                               | Added |
| -------------------------------------------------------------------------------------------------------------------- | ----- |
| [Link](https://github.com/pyblish/pyblish-base/blob/f695fad94b995915495b4123c503f24d3419429a/pyblish/plugin.py#L350) | 1.3.0 |

Inherits [Plugin](/pyblish.api/plugin)

## Public Functions

| Output | Method                                                                                           |
| -----: | ------------------------------------------------------------------------------------------------ |
|        | [process](/pyblish.api/instanceplugin/instanceplugin.process)([instance](/pyblish.api/instance)) |

## Usage

The `InstancePlugin` is used for processing each individual instance. It is typically used on [Instances](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/instance.md) created during [Collection](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/CollectorOrder/README.md), either to validate or extract, but can be thought of as just a general process on each available [Instance](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/instance.md).

## Example

```python
import pyblish.api as pyblish

class MyValidator(pyblish.InstancePlugin):
    order = pyblish.ValidatorOrder

    def process(self, instance):
        assert instance.data["name"] == "MyInstance"
```


# .process

## InstancePlugin.process

The primary processing mechanism of the [Instnace](/pyblish.api/instance).

### Introduction

This method may be overridden in your plug-in subclasses to process the current [Instance](/pyblish.api/instance).

## Example

```python
import pyblish.api

class ValidateInstances(pyblish.api.InstancePlugin):
    order = pyblish.api.ValidatorOrder

    def process(self, instance):
        assert instance.data["name"] == "MyInstance"
```


# Action

Process once, with [Context](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/context.md) and [Plugin](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/plugin.md) as input.

| Source                                                                                          | Added |
| ----------------------------------------------------------------------------------------------- | ----- |
| [Link](https://github.com/pyblish/pyblish-base/commit/ac83f2a94bbde95bc2f6c4000d7c50e36a3d3b5f) | 1.2.0 |

Inherits [Plugin](/pyblish.api/plugin)

## Public Functions

| Output | Method                                                                                                                                                                                               |
| -----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|        | [process](/pyblish.api/contextplugin/contextplugin.process)([context](/pyblish.api/context), [plugin](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/plugin.md)) |

## Properties

| property                                | type |
| --------------------------------------- | ---- |
| [icon](/pyblish.api/action/action.icon) | str  |
| [on](/pyblish.api/action/action.on)     | str  |

## Usage

Attach any functionality to a plug-in and tailor it to a particular state; like an action only available via a failed validator, or a successful extraction, or just all-round functionality associated with a particular plug-in.

![image](https://cloud.githubusercontent.com/assets/2152766/13439097/da8cf9da-dfe3-11e5-8db1-7c33f31046fd.png)

Each action is passed both the Context and it's parent plug-in at run-time and can be accessed via their argument signature, similar to plug-ins.

Actions in QML are arranged in a menu with optional customisable groups and separators. Actions with any kind of implementation error show up as well, including a helpful error message for simplified debugging.

**Argument signature**

These objects are available via the argument signature.

* `context`: The global context
* `plugin`: The parent plug-in

**Full list of features**

* Per-plugin actions
* Action API \~= Plug-in API, it is more or less a 1-1 match between their interfaces, including `process()` and `label`.
* Standard logging and exception reporting, identical to plug-ins
* Customisable icon per action, from [Awesome Icon](http://fortawesome.github.io/Font-Awesome/icons/)
* Customisable availability
  * `all`: Always
  * `processed`: After plug-in has been processed
  * `failed`: After plug-in has been processed, and failed
  * `succeeded`: After plug-in has been processed, and succeeded

## Example

```python
class OpenInExplorer(pyblish.api.Action):
    label = "Open in Explorer"
    on = "failed"  # This action is only available on a failed plug-in
    icon = "hand-o-up"  # Icon from Awesome Icon

    def process(self, context, plugin):
        import subprocess
        subprocess.call("start .", shell=True)  # Launch explorer at the cwd


class Validate(pyblish.api.InstancePlugin):
    order = pyblish.api.ValidatorOrder
    actions = [
        # Order of items is preserved
        pyblish.api.Category("My Actions"),
        MyAction,
        pyblish.api.Separator,
    ]

    def process(self, instance):
        self.log.info("Standard log messages apply here.")
        raise Exception("Exceptions too.")
```

## Extended Example

Every possible combination of an action.

```python
class ContextAction(pyblish.api.Action):
    label = "Context action"

    def process(self, context):
        self.log.info("I have access to the context")
        self.log.info("Context.instances: %s" % str(list(context)))


class FailingAction(pyblish.api.Action):
    label = "Failing action"

    def process(self, context, plugin):
        self.log.info("About to fail..")
        raise Exception("I failed")


class LongRunningAction(pyblish.api.Action):
    label = "Long-running action"

    def process(self, context, plugin):
        self.log.info("Sleeping for 2 seconds..")
        time.sleep(2)
        self.log.info("Ah, that's better")


class IconAction(pyblish.api.Action):
    label = "Icon action"
    icon = "crop"

    def process(self, context, plugin):
        self.log.info("I have an icon")


class PluginAction(pyblish.api.Action):
    label = "Plugin action"

    def process(self, context, plugin):
        self.log.info("I have access to my parent plug-in")
        self.log.info("Which is %s" % plugin.id)


class LaunchExplorerAction(pyblish.api.Action):
    label = "Open in Explorer"
    icon = "folder-open"

    def process(self, context, plugin):
        import os
        import subprocess

        cwd = context.data["cwd"]
        self.log.info("Opening %s in Explorer" % cwd)
        result = subprocess.call("start .", cwd=cwd, shell=True)
        self.log.debug(result)


class ProcessedAction(pyblish.api.Action):
    label = "Success action"
    icon = "check"
    on = "processed"

    def process(self, context, plugin):
        self.log.info("I am only available on a successful plug-in")


class FailedAction(pyblish.api.Action):
    label = "Failure action"
    icon = "close"
    on = "failed"


class SucceededAction(pyblish.api.Action):
    label = "Success action"
    icon = "check"
    on = "succeeded"

    def process(self, context, plugin):
        self.log.info("I am only available on a successful plug-in")


class BadEventAction(pyblish.api.Action):
    label = "Bad event action"
    on = "not exist"


class InactiveAction(pyblish.api.Action):
    active = False


class PluginWithActions(pyblish.api.InstancePlugin):
    order = pyblish.api.ValidatorOrder
    optional = True
    actions = [
        pyblish.api.Category("General"),
        ContextAction,
        FailingAction,
        LongRunningAction,
        IconAction,
        PluginAction,
        pyblish.api.Category("OS"),
        LaunchExplorerAction,
        pyblish.api.Separator,
        FailedAction,
        SucceededAction,
        pyblish.api.Category("Debug"),
        BadEventAction,
        InactiveAction,
    ]

    def process(self, instance):
        self.log.info("Ran PluginWithActions")
```

## Maya Example

```python
import time
import pyblish.api
import pyblish_qml


class Collect(pyblish.api.Collector):
    def process(self, context):
        i = context.create_instance("MyInstance")
        i.data["family"] = "default"
        i.append("pCube1")


class SelectInvalidNodes(pyblish.api.Action):
    label = "Select broken nodes"
    on = "failed"
    icon = "hand-o-up"

    def process(self, context):
        self.log.info("Finding bad nodes..")
        nodes = []
        for result in context.data["results"]:
            if result["error"]:
                instance = result["instance"]
                nodes.extend(instance)

        self.log.info("Selecting bad nodes: %s" % ", ".join(nodes))
        cmds.select(deselect=True)
        cmds.select(nodes)


class Validate(pyblish.api.Validator):
    actions = [
        pyblish.api.Category("Scene"),
        SelectInvalidNodes
    ]

    def process(self, instance):
        raise Exception("I failed")


pyblish.api.register_plugin(Collect)
pyblish.api.register_plugin(Validate)

import pyblish_maya
pyblish_maya.show()
```

{{ file.mtime }}


# .process

## Action.process

The primary processing mechanism of the Action.

### Introduction

Override this to provide wanted functionality when executing this action.

## Example

```python
import pyblish.api

class MyAction(pyblish.api.Action):
    def process(self):
        print("Running action")


class ActionWithContext(pyblish.api.Action):
    def process(self, context):
        print("Running action with context")


class ActionWithPlugin(pyblish.api.Action):
    def process(self, plugin):
        print("Running action with plugin")


class ActionWithContextAndPlugin(pyblish.api.Action):
    def process(self, context, plugin):
        print("Running action with context and plug-in")
```


# .icon

Customisable icon to go with an Action.

## Description

Associate an [FontAwesome](http://fortawesome.github.io/Font-Awesome/icons) icon with an action. Choose from the library of available icons on from the main website.

* [FontAwesome Library](http://fortawesome.github.io/Font-Awesome/icons)

## Example

```python
class MyAction(pyblish.api.Action):
    icon = "close"
```


# .on

Tailor the circumstance upon which a particular action should be made available.

## Description

Sometimes an Action is not relevant until a certain precondition has been met. For example, if an action is meant to repair broken validation, then it makes the most sense to provide this functionality until validation has actually failed.

## Example

```python
import pyblish.api

class MyAction(pyblish.api.Action):
    on = "failed"
```


# Category

A visual separator for the parent menu of [Actions](/pyblish.api/action).

## Public Functions

| Output | Method             |
| -----: | ------------------ |
|        | \_\_init\_\_(name) |

## Example

```python
import pyblish.api


class OpenInExplorer(pyblish.api.Action):
    label = "Open in Explorer"
    on = "failed" plug-in
    icon = "hand-o-up"

    def process(self, context):
        import subprocess
        subprocess.call("start .", shell=True)


class Validate(pyblish.api.Validator):
    actions = [
        # Order of items is preserved
        pyblish.api.Category("My Actions"),
        MyAction,
        pyblish.api.Separator,
    ]

    def process(self, context, plugin):
        raise Exception("Failed")
```


# Separator

A visual separator for the parent menu of [Actions](/pyblish.api/action).

## Example

```python
import pyblish.api


class OpenInExplorer(pyblish.api.Action):
    label = "Open in Explorer"
    on = "failed" plug-in
    icon = "hand-o-up"

    def process(self, context):
        import subprocess
        subprocess.call("start .", shell=True)


class Validate(pyblish.api.Validator):
    actions = [
        # Order of items is preserved
        pyblish.api.Category("My Actions"),
        MyAction,
        pyblish.api.Separator,
    ]

    def process(self, context, plugin):
        raise Exception("Failed")
```


# discover

The primary mechanism with which plug-ins are read from disk.

## Introduction

Pyblish is a plug-in driven framework, everything it does it does through plug-ins. A plug-in can either come in the form of a declaration in the currently active Python session, or as a file. This discovery mechanism is how plug-ins are located and loaded dynamically into Pyblish at run-time.

## Mechanism

For Pyblish to locate plug-ins, you either (1) register a plug-in directly via [register\_plugin](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/register_plugin.md), (2) register a path via [PYBLISHPLUGINPATH](/environment-variables/pyblishpluginpath) or (3) [register\_plugin\_path](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/register_plugin_path.md).

Registering a plug-in directly (1) is useful during initial prototyping and for sharing your plug-in with others in a quick and effortless manner. You can simply post your plug-in on a forum, one could copy-paste it into his running session of Python and off we go. Registering directories (2)(3) makes for a power method of persisting plug-ins and to dynamically expose plug-in based on project, task and/or artist.


# sort

Sort a list of plug-ins in-place.

| Source     | Added  |
| ---------- | ------ |
| \[Link]\[] | 1.0.16 |

\[Link]: <https://github.com/pyblish/pyblish/blob/master/pyblish/plugin.py#L960>


# register\_gui

## register\_gui

Register interest in a graphical user interface.

| Source | Added |
| ------ | ----- |
|        | 1.4.1 |

## Functions

| Output | Method                                                                                                                              |
| -----: | ----------------------------------------------------------------------------------------------------------------------------------- |
|        | [register\_gui](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/register_gui/README.md)(str)     |
|        | [deregister\_gui](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/deregister_gui/README.md)(str) |
|        | [registered\_guis](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/registered_guis/README.md)()  |

## Description

Register one or more Python packages with the following interface, and surrounding Pyblish projects may utilise them where needed. Such as in file menu of the Autodesk Maya integration.

**Interface**

```python
def show():
  """Create or unhide the most desireable GUI."""
```

Multiple GUIs may be registered, it is up to the consumer of the registered GUIs to determine which to use and how. The design intent is to enable registration of a series of default GUIs, along with custom or bespoke ones.

```python
>>> import pyblish.api
>>> pyblish.api.registered_guis()
['my_personal_gui', 'pyblish_qml', 'pyblish_lite']
```

## Example

Here is the basic structure expected by the `register_gui` function.

```yaml
my_package/
  __init__.py
```

**\_\_init\_\_.py**

```python
"""My package description"""

from PySide import QtGui

def show():
    my_gui = QtGui.QMessageBox()
    my_gui.show()
```

Once the package is on your `PYTHONPATH`, you may register it like so.

```python
pyblish.api.register_gui("my_package")
```

{{ file.mtime }}


# register\_host

## register\_host

Register supported host.

| Source | Added |
| ------ | ----- |
|        | 1.1.3 |

## Functions

| Output | Method                                                                                                                                |
| -----: | ------------------------------------------------------------------------------------------------------------------------------------- |
|        | [register\_host](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/register_gui/README.md)(str)      |
|        | [deregister\_host](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/deregister_host/README.md)(str) |
|        | [registered\_hosts](https://github.com/pyblish/api/tree/9d41e509649f2dfb91bc4d595aebabed2dc0512f/pages/registered_hosts/README.md)()  |

## Description

Limit availability of plug-ins by host, such as Maya.

Integrations, such as `pyblish-maya` and `pyblish-nuke` register their own corresponding host automatically. Additional hosts may be registered by the end-user to customise the available plug-ins at time of publish.

## Example

```python
from pyblish import api

class CollectObjectSets(api.ContextPlugin):
    """Collect things only Maya would know"""
    order = api.CollectorOrder
    hosts = ["maya"]
    def process(self, context):
        from maya import cmds
        for objset in cmds.ls(type="objectSet"):
        context.create_instance(objset)
```

{{ file.mtime }}


# Introduction

![image](https://cloud.githubusercontent.com/assets/2152766/6998101/5c13946c-dbcd-11e4-968b-b357b7c60a06.png)

Welcome to the API documentation for Pyblish.

Choose a version of the library you would like to explore to the left.


# v1.2


# v1.3


# v1.4


