Skip to content

simpletypes

simpletypes

Simple-type classes, corresponding to ST_* schema items.

These provide validation and format translation for values stored in XML element attributes. Naming generally corresponds to the simple type in the associated XML schema.

BaseSimpleType

Base class for simple-types.

XsdAnyUri

Bases: BaseStringType

There's a regex in the spec this is supposed to meet...

but current assessment is that spending cycles on validating wouldn't be worth it for the number of programming errors it would catch.

XsdId

Bases: BaseStringType

String that must begin with a letter or underscore and cannot contain any colons.

Not fully validated because not used in external API.

XsdStringEnumeration

Bases: BaseStringEnumerationType

Set of enumerated xsd:string values.

XsdToken

Bases: BaseStringType

Xsd:string with whitespace collapsing, e.g. multiple spaces reduced to one, leading and trailing space stripped.

ST_DateTime

Bases: BaseSimpleType

convert_from_xml classmethod

convert_from_xml(str_value: str) -> datetime

Convert an xsd:dateTime string to a datetime object.

Source code in src/docx/oxml/simpletypes.py
@classmethod
def convert_from_xml(cls, str_value: str) -> dt.datetime:
    """Convert an xsd:dateTime string to a datetime object."""

    def parse_xsd_datetime(dt_str: str) -> dt.datetime:
        # -- handle trailing 'Z' (Zulu/UTC), common in Word files --
        if dt_str.endswith("Z"):
            try:
                # -- optional fractional seconds case --
                return dt.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%S.%fZ").replace(
                    tzinfo=dt.timezone.utc
                )
            except ValueError:
                return dt.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ").replace(
                    tzinfo=dt.timezone.utc
                )

        # -- handles explicit offsets like +00:00, -05:00, or naive datetimes --
        try:
            return dt.datetime.fromisoformat(dt_str)
        except ValueError:
            # -- fall-back to parsing as naive datetime (with or without fractional seconds) --
            try:
                return dt.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%S.%f")
            except ValueError:
                return dt.datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%S")

    try:
        # -- parse anything reasonable, but never raise, just use default epoch time --
        return parse_xsd_datetime(str_value)
    except Exception:
        return dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)

ST_WrapDistance

Bases: XsdUnsignedInt

Distance in EMU held clear of a floating shape when text wraps around it.

The distT, distB, distL and distR attributes of wp:anchor. Exchanged as Length so it composes with Pt(), Inches() and the rest.

ST_EighthPointMeasure

Bases: XsdUnsignedLong

Measure in eighths of a point, e.g. "4" is half a point.

Used for border widths (w:sz on w:tblBorders/w:top and friends). Values are exchanged as Length so they compose with Pt(), Inches() and the rest.

ST_PointMeasure

Bases: XsdUnsignedLong

Measure in whole points, e.g. "4" is four points.

Used for the offset of a border from the text it surrounds (w:space). Values are exchanged as Length, as for ST_EighthPointMeasure.

ST_FldCharType

Bases: XsdStringEnumeration

Valid values for the w:fldChar/@w:fldCharType attribute.

ST_FtnEdn

Bases: XsdStringEnumeration

Valid values for the w:footnote/@w:type and w:endnote/@w:type attributes.

ST_HexColor

Bases: BaseStringType

ST_HexColor, a union of an RGB triple and the literal "auto".

ref/xsd/wml.xsd:159 defines it as <xsd:union memberTypes="ST_HexColorAuto s:ST_HexColorRGB"/>, so "auto" — meaning "let the consumer choose a colour that contrasts with the background" — is as valid as a hex triple. Both directions accept it; converting one way only would make a value readable and not writable.

convert_to_xml classmethod

convert_to_xml(value: RGBColor | str) -> str

Keep alpha hex numerals all uppercase just for consistency.

Source code in src/docx/oxml/simpletypes.py
@classmethod
def convert_to_xml(  # pyright: ignore[reportIncompatibleMethodOverride]
    cls, value: RGBColor | str
) -> str:
    """Keep alpha hex numerals all uppercase just for consistency."""
    if value == ST_HexColorAuto.AUTO:
        return ST_HexColorAuto.AUTO
    # expecting 3-tuple of ints in range 0-255
    return "%02X%02X%02X" % cast(RGBColor, value)

ST_HexColorAuto

Bases: XsdStringEnumeration

Value for `w:color/[@val="auto"] attribute setting.

ST_HpsMeasure

Bases: XsdUnsignedLong

Half-point measure, e.g. 24.0 represents 12.0 points.

The schema type is a union of an unsigned decimal count of half-points and a universal measure like "12pt". A fractional count of half-points such as "21.5" is not strictly valid, but Word reads it and several other generators write it, so it is accepted here and rounded to the nearest EMU.

convert_to_xml classmethod

convert_to_xml(value: int | Length) -> str

Round to the nearest half-point rather than truncating.

A half-point count is always written as an integer, since a fractional value is outside the schema type even though it is accepted on read.

Source code in src/docx/oxml/simpletypes.py
@classmethod
def convert_to_xml(cls, value: int | Length) -> str:
    """Round to the nearest half-point rather than truncating.

    A half-point count is always written as an integer, since a fractional value is
    outside the schema type even though it is accepted on read.
    """
    emu = Emu(value)
    half_points = int(round(emu.pt * 2))
    return str(half_points)

ST_Merge

Bases: XsdStringEnumeration

Valid values for attribute.

ST_PageBorderDisplay

Bases: XsdStringEnumeration

Valid values for w:pgBorders/@w:display.

ST_PageBorderOffset

Bases: XsdStringEnumeration

Valid values for w:pgBorders/@w:offsetFrom.

ST_PageBorderZOrder

Bases: XsdStringEnumeration

Valid values for w:pgBorders/@w:zOrder.

ST_MeasurementOrPercent

Bases: XsdInt

The w:w attribute of w:tblW, w:tcW, w:tblInd and the rest of CT_TblWidth.

What the number means depends on the sibling w:type attribute, which an attribute converter cannot see, so this type stays deliberately literal and hands back a plain int: twips for w:type="dxa", fiftieths of a percent for "pct". CT_TblWidth is where the two are told apart.

The schema also admits "50%" and universal measures such as "1.5in". Word writes neither, but documents from other producers do, so both are converted to the plain form on the way in.

ST_ShortHexNumber

Bases: BaseSimpleType

A two-byte value written as four hexadecimal digits, e.g. "04A0".

Used for the legacy bitmask on w:tblLook/@w:val. Exchanged as an int.

ST_TextScalePercent

Bases: XsdInt

Horizontal character scaling, as a whole percentage of normal width.

ECMA-376 constrains w:w/@w:val to 1..600; Word rejects values outside that.

ST_VerticalAlignRun

Bases: XsdStringEnumeration

Valid values for w:vertAlign/@val.