
Temporal is a distributed, scalable, durable, and highly available orchestration engine used to
execute asynchronous, long-running business logic in a scalable and resilient way.
"Temporal Python SDK" is the framework for authoring workflows and activities using the Python programming language.
Also see:
In addition to features common across all Temporal SDKs, the Python SDK also has the following interesting features:
Type Safe
This library uses the latest typing and MyPy support with generics to ensure all calls can be typed. For example,
starting a workflow with an int parameter when it accepts a str parameter would cause MyPy to fail.
Different Activity Types
The activity worker has been developed to work with async def, threaded, and multiprocess activities. Threaded activities are the initial recommendation, and further guidance can be found in the docs.
Custom asyncio Event Loop
The workflow implementation basically turns async def functions into workflows backed by a distributed, fault-tolerant
event loop. This means task management, sleep, cancellation, etc have all been developed to seamlessly integrate with
asyncio concepts.
See the blog post introducing the Python SDK for an
informal introduction to the features and their implementation.
Contents
- Quick Start
- Installation
- Implementing a Workflow
- Running a Workflow
- Next Steps
- Usage
- Client
- Data Conversion
- Pydantic Support
- Custom Type Data Conversion
- External Storage
- Driver Selection
- Built-in Drivers
- Custom Drivers
- Workers
- Workflows
- Definition
- Running
- Invoking Activities
- Invoking Child Workflows
- Timers
- Conditions
- Asyncio and Determinism
- Asyncio Cancellation
- Workflow Utilities
- Exceptions
- Signal and update handlers
- External Workflows
- Testing
- Automatic Time Skipping
- Manual Time Skipping
- Mocking Activities
- Workflow Sandbox
- How the Sandbox Works
- Avoiding the Sandbox
- Customizing the Sandbox
- Passthrough Modules
- Invalid Module Members
- Debugging Workflows with
breakpoint() / pdb
- Known Sandbox Issues
- Global Import/Builtins
- Sandbox is not Secure
- Sandbox Performance
- Extending Restricted Classes
- Certain Standard Library Calls on Restricted Objects
- is_subclass of ABC-based Restricted Classes
- Activities
- Definition
- Types of Activities
- Synchronous Activities
- Synchronous Multithreaded Activities
- Synchronous Multiprocess/Other Activities
- Asynchronous Activities
- Activity Context
- Heartbeating and Cancellation
- Worker Shutdown
- Testing
- Interceptors
- Nexus
- Plugins
- Usage
- Plugin Implementations
- Advanced Plugin Implementations
- Client Plugins
- Worker Plugins
- Workflow Replay
- Observability
- Metrics
- OpenTelemetry Tracing
- OpenTelemetry Metrics
- Protobuf compatibility
- Known Compatibility Issues
- Development
- Building
- Prepare
- Build
- Use
- FIPS Compliance (Experimental)
- Local SDK development environment
- Testing
- Proto Generation and Testing
- Style
Quick Start
We will guide you through the Temporal basics to create a "hello, world!" script on your machine. It is not intended as
one of the ways to use Temporal, but in reality it is very simplified and decidedly not "the only way" to use Temporal.
For more information, check out the docs references in "Next Steps" below the quick start.
Installation
Install the temporalio package from PyPI.
These steps can be followed to use with a virtual environment and pip:
- Create a virtual environment
- Update
pip - python -m pip install -U pip
- Needed because older versions of
pip may not pick the right wheel
- Install Temporal SDK -
python -m pip install temporalio
The SDK is now ready for use. To build from source, see "Building" near the end of this documentation.
NOTE: This README is for the current branch and not necessarily what's released on PyPI.
Implementing a Workflow
Create the following in activities.py:
from temporalio import activity
@activity.defn
def say_hello(name: str) -> str:
return f"Hello, {name}!"
Create the following in workflows.py:
from datetime import timedelta
from temporalio import workflow
# Import our activity, passing it through the sandbox
with workflow.unsafe.imports_passed_through():
from activities import say_hello
@workflow.defn
class SayHello:
@workflow.run
async def run(self, name: str) -> str:
return await workflow.execute_activity(
say_hello, name, schedule_to_close_timeout=timedelta(seconds=5)
)
Create the following in run_worker.py:
import asyncio
import concurrent.futures
from temporalio.client import Client
from temporalio.worker import Worker
# Import the activity and workflow from our other files
from activities import say_hello
from workflows import SayHello
async def main():
# Create client connected to server at the given address
client = await Client.connect("localhost:7233")
# Run the worker
with concurrent.futures.ThreadPoolExecutor(max_workers=100) as activity_executor:
worker = Worker(
client,
task_queue="my-task-queue",
workflows=[SayHello],
activities=[say_hello],
activity_executor=activity_executor,
)
await worker.run()
if __name__ == "__main__":
asyncio.run(main())
Assuming you have a Temporal server running on localhost, this
will run the worker:
python run_worker.py
Running a Workflow
Create the following script at run_workflow.py:
import asyncio
from temporalio.client import Client
# Import the workflow from the previous code
from workflows import SayHello
async def main():
# Create client connected to server at the given address
client = await Client.connect("localhost:7233")
# Execute a workflow
result = await client.execute_workflow(SayHello.run, "my name", id="my-workflow-id", task_queue="my-task-queue")
print(f"Result: {result}")
if __name__ == "__main__":
asyncio.run(main())
Assuming you have run_worker.py running from before, this will run the workflow:
python run_workflow.py
The output will be:
Result: Hello, my-name!
Next Steps
Temporal can be implemented in your code in many different ways, to suit your application's needs. The links below will
give you much more information about how Temporal works with Python:
- Code Samples - If you want to start with some code, we have provided
some pre-built samples.
- Application Development Guide Our Python specific
Developer's Guide will give you much more information on how to build with Temporal in your Python applications than
our SDK README ever could (or should).
- API Documentation - Full Temporal Python SDK package documentation.
Usage
From here, you will find reference documentation about specific pieces of the Temporal Python SDK that were built around
Temporal concepts. This section is not intended as a how-to guide -- For more how-to oriented information, check out
the links in the Next Steps section above.
Client
A client can be created and used to start a workflow like so:
from temporalio.client import Client
async def main():
# Create client connected to server at the given address and namespace
client = await Client.connect("localhost:7233", namespace="my-namespace")
# Start a workflow
handle = await client.start_workflow(MyWorkflow.run, "some arg", id="my-workflow-id", task_queue="my-task-queue")
# Wait for result
result = await handle.result()
print(f"Result: {result}")
Some things to note about the above code:
- A
Client does not have an explicit "close"
- To enable TLS, the
tls argument to connect can be set to True or a TLSConfig object
- A single positional argument can be passed to
start_workflow. If there are multiple arguments, only the
non-type-safe form of start_workflow can be used (i.e. the one accepting a string workflow name) and it must be in
the args keyword argument.
- The
handle represents the workflow that was started and can be used for more than just getting the result
- Since we are just getting the handle and waiting on the result, we could have called
client.execute_workflow which
does the same thing
- Clients can have many more options not shown here (e.g. data converters and interceptors)
- A string can be used instead of the method reference to call a workflow by name (e.g. if defined in another language)
- Clients do not work across forks
Clients also provide a shallow copy of their config for use in making slightly different clients backed by the same
connection. For instance, given the client above, this is how to have a client in another namespace:
config = client.config()
config["namespace"] = "my-other-namespace"
other_ns_client = Client(**config)
Data Conversion
Data converters are used to convert raw Temporal payloads to/from actual Python types. A custom data converter of type
temporalio.converter.DataConverter can be set via the data_converter parameter of the Client constructor. Data
converters are a combination of payload converters, external storage, payload codecs, and failure converters. Payload
converters convert Python values to/from serialized bytes. External payload storage optionally stores and retrieves payloads
to/from external storage services using drivers. Payload codecs convert bytes to bytes (e.g. for compression or encryption).
Failure converters convert exceptions to/from serialized failures.
The default data converter supports converting multiple types including:
None
bytes
google.protobuf.message.Message - As JSON when encoding, but has ability to decode binary proto from other languages
- Anything that can be converted to JSON including:
- Anything that
json.dump supports natively
- dataclasses
- Iterables including ones JSON dump may not support by default, e.g.
set
- IntEnum, StrEnum based enumerates, including enums that mix in
int or str
- UUID
datetime.datetime
To use pydantic model instances, see Pydantic Support.
datetime.date and datetime.time can only be used with the Pydantic data converter.
Although workflows, updates, signals, and queries can all be defined with multiple input parameters, users are strongly
encouraged to use a single dataclass or Pydantic model parameter, so that fields with defaults can be easily added
without breaking compatibility. Similar advice applies to return values.
Classes with generics may not have the generics properly resolved. The current implementation does not have generic
type resolution. Users should use concrete types.
Pydantic Support
To use Pydantic model instances, install Pydantic and set the Pydantic data converter when creating client instances:
from temporalio.contrib.pydantic import pydantic_data_converter
client = Client(data_converter=pydantic_data_converter, ...)
This data converter supports conversion of all types supported by Pydantic to and from JSON.
In addition to Pydantic models, these include all json.dump-able types, various non-json.dump-able standard library
types such as dataclasses, types from the datetime module, sets, UUID, etc, and custom types composed of any of these.
Pydantic v1 is not supported by this data converter. If you are not yet able to upgrade from Pydantic v1, see
https://github.com/temporalio/samples-python/tree/main/pydantic_converter/v1 for limited v1 support.
Custom Type Data Conversion
For converting from JSON, the workflow/activity type hint is taken into account to convert to the proper type. Care has
been taken to support all common typings including Optional, Union, all forms of iterables and mappings, NewType,
etc in addition to the regular JSON values mentioned before.
Data converters contain a reference to a payload converter class that is used to convert to/from payloads/values. This
is a class and not an instance because it is instantiated on every workflow run inside the sandbox. The payload
converter is usually a CompositePayloadConverter which contains a multiple EncodingPayloadConverters it uses to try
to serialize/deserialize payloads. Upon serialization, each EncodingPayloadConverter is tried until one succeeds. The
EncodingPayloadConverter provides an "encoding" string serialized onto the payload so that, upon deserialization, the
specific EncodingPayloadConverter for the given "encoding" is used.
The default data converter uses the DefaultPayloadConverter which is simply a CompositePayloadConverter with a known
set of default EncodingPayloadConverters. To implement a custom encoding for a custom type, a new
EncodingPayloadConverter can be created for the new type. For example, to support IPv4Address types:
class IPv4AddressEncodingPayloadConverter(EncodingPayloadConverter):
@property
def encoding(self) -> str:
return "text/ipv4-address"
def to_payload(self, value: Any) -> Optional[Payload]:
if isinstance(value, ipaddress.IPv4Address):
return Payload(
metadata={"encoding": self.encoding.encode()},
data=str(value).encode(),
)
else:
return None
def from_payload(self, payload: Payload, type_hint: Optional[Type] = None) -> Any:
assert not type_hint or type_hint is ipaddress.IPv4Address
return ipaddress.IPv4Address(payload.data.decode())
class IPv4AddressPayloadConverter(CompositePayloadConverter):
def __init__(self) -> None:
# Just add ours as first before the defaults
super().__init__(
IPv4AddressEncodingPayloadConverter(),
*DefaultPayloadConverter.default_encoding_payload_converters,
)
my_data_converter = dataclasses.replace(
DataConverter.default,
payload_converter_class=IPv4AddressPayloadConverter,
)
Imports are left off for brevity.