Python · recipe

Write a value to an OPC UA server in Python

Match the node's DataType exactly or the write fails. Read the DataType attribute first, build a Variant of that type, and check the returned status rather than assuming success. The umati server is read-only, so use a local server for this.

Stackasyncua (FreeOpcUa/opcua-asyncio)
Version2.0.1

The code

import asyncio
from asyncua import Client, ua

# umati is read-only. Start a local server first:
#   uaserver --populate
URL = "opc.tcp://localhost:4840/freeopcua/server/"

async def main():
    async with Client(url=URL) as client:
        node = client.get_node("ns=2;i=2")
        dtype = await node.read_data_type_as_variant_type()
        print("node expects:", dtype)
        await node.write_value(ua.DataValue(ua.Variant(42, dtype)))
        print("read back   :", await node.read_value())

asyncio.run(main())

What it prints

node expects: VariantType.Int64
read back   : 42

Notes

  • `read_data_type_as_variant_type()` removes the guesswork. Int16 is not Int32, and a scalar is not a one-element array.
  • Check AccessLevel before writing. Some servers accept a write, return Good, and discard it: the umati sample server does this deliberately, so always read back in a test.
  • For an array node, write the whole array or use an IndexRange. Writing a scalar to an array node is a type mismatch, not a partial write.
  • CLI equivalent: `uawrite -u <url> -n "ns=2;i=2" 42`.

What breaks first

The write is rejected because the Variant type does not match the node's DataType BadTypeMismatch
Read the DataType attribute and construct the Variant with that exact type. Do not rely on Python's int or float mapping to what the server wants.

Last verified 7 September 2026 against OPC UA 1.05.07. OPC UA Connect is an educational resource and is not affiliated with the OPC Foundation.

Free download
OPC UA Troubleshooting & Integration Checklist
The field-tested checklist engineers use to diagnose certificates, ports and namespace problems fast, plus a Python (asyncua) client template.
Get the free checklist →
Free, no course, no login