Skip to content

Python attribute type annotations use inappropriate <em> tags, breaking semantic HTML #13688

Open
@q2mark

Description

@q2mark

Problem

Sphinx currently wraps Python attribute type annotations and default values in <em class="property"> tags, which creates inappropriate semantic HTML where punctuation (colons, equals signs) and type information are italicized.

Current Behavior

For a Python attribute like:

.. py:attribute:: name
   :type: str
   :value: "default_value"

Sphinx generates:

<span class="sig-name descname">name</span>
<em class="property">: str</em>
<em class="property"> = "default_value"</em>

Issues This Causes

  1. Poor semantic HTML: Punctuation (: and =) shouldn't be emphasized
  2. Visual problems: Colons and equals signs appear italicized in browsers
  3. Markdown conversion issues: Documentation crawlers/converters produce messy output like:
    name*: `str`* *= "default_value"*
    
  4. Accessibility concerns: Screen readers may interpret emphasis incorrectly

Expected Behavior

Type annotations should use <span class="property"> instead of <em class="property">:

<span class="sig-name descname">name</span>
<span class="property">: str</span>
<span class="property"> = "default_value"</span>

Environment

  • Sphinx version: 8.2.3 (affects all versions)
  • Python version: Any
  • Operating system: Any

Root Cause

The issue is in sphinx/writers/html5.py lines 307-311:

def visit_desc_annotation(self, node: Element) -> None:
    self.body.append(self.starttag(node, 'em', '', CLASS='property'))

def depart_desc_annotation(self, node: Element) -> None:
    self.body.append('</em>')

Proposed Solution

Replace em with span to maintain CSS styling while fixing semantic HTML:

def visit_desc_annotation(self, node: Element) -> None:
    self.body.append(self.starttag(node, 'span', '', CLASS='property'))

def depart_desc_annotation(self, node: Element) -> None:
    self.body.append('</span>')

Additional Context

This aligns with Sphinx's recent efforts to improve semantic HTML structure, similar to the work done in issues #4390 (consistent CSS for signatures) and #13454 (CSS classes for method types).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions