class towhee.engine.operator_registry.OperatorRegistry[source]

Bases: object

Operator Registry



Register a class, function, or callable as a towhee operator.


Resolve operator by name




Initialize self. See help(type(self)) for accurate signature.

static register(name: Optional[str] = None, input_schema=None, output_schema=None, flag=None)[source]

Register a class, function, or callable as a towhee operator.


  1. register a function as operator

>>> from towhee import register
>>> @register
... def foo(x, y):
...     return x+y
  1. register a class as operator

>>> @register
... class foo_cls():
...     def __init__(self, x):
...         self.x = x
...     def __call__(self, y):
...         return self.x + y

By default, function/class name is used as operator name, which is used by the operator factory towhee.ops to invoke the operator.

>>> from towhee import ops
>>> op =
>>> op(1, 2)
>>> op = ops.foo_cls(x=2)
>>> op(3)
  1. register operator with an alternative name:

>>> @register(name='my_foo')
... def foo(x, y):
...     return x+y
>>> ops.my_foo()(1,2)

Operator URI and Namespace: The URI (unique reference identifier) of an operator has two parts: namespace and name. The namespace helps identify one operator and group the operators into various kinds. We can specific the namespace when create an operator:

>>> ops.anon.my_foo()(1,2)

anon is the default namespace to which an operator is registered if no namespace is specified. And it’s also the default searching namespace for the operator factory.

You can also specific the fullname, including namespace when register an operator:

>>> @register(name='my_namespace/my_foo')
... def foo(x, y):
...     return x+y
>>> ops.my_namespace.my_foo()(1,2)

Output Schema:

>>> @register(name='my_foo', output_schema='value')
... def foo(x, y):
...     return x+y
>>> from towhee.hparam import param_scope
>>> with param_scope('towhee.need_schema=1'):
...     ops.my_foo()(1,2)

Flag: Each operator type, for example: NNOperator and PyOperator, has their own default flag:

>>> from towhee.operator.base import Operator, NNOperator, PyOperator
>>> from towhee.operator.base import OperatorFlag
>>> @register
... class foo(NNOperator):
...     pass
>>> foo().flag

The default flag can be override by register(flag=someflag):

>>> @register(flag=OperatorFlag.EMPTYFLAG)
... class foo(NNOperator):
...     pass
>>> foo().flag
<OperatorFlag.EMPTYFLAG: 1>
  • name (str, optional) – operator name, will use the class/function name if None.

  • input_schema (NamedTuple, optional) – input schema for the operator. Defaults to None.

  • output_schema (NamedTuple, optional) – output schema, will convert the operator output to NamedTuple if not None.

  • flag ([OperatorFlag], optional) – operator flag. Defaults to OperatorFlag.EMPTYFLAG.



Return type:


static resolve(name: str)Any[source]

Resolve operator by name