How do I modify the attributes of ? I need to be able to change attributes (like class, data-toggle, data-direction) of the label itself, at a PHP level, in a way that will support conditions in form definition function.

The solution given in How can I add a class to a label? doesn't work for my problem, as they are only workarounds that will not work with the theming JavaScript I need to expose my data to. Also, they are pretty much limited to styling, and that's only one of the attributes that may be needed.

I'm OK with only having limited, predefined sets of attributes, as long as I can select one at the time of form building.
Solution is to implement theme_form_element_label. 

Changing one line from:

$attributes = array();


to:

$attributes = isset($element['#label_attributes'])?$element['#label_attributes']:array();


in your implementation makes it possible to use '#label_attributes' just the way you would use normal #attributes.

NOTE: If your parent theme defines this function already, then you need to copy function from parent theme, not from form.inc.



Full implementation, to put in template.php:

function mymodule_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') &amp;&amp; empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' =&gt; $element)) : '';

  $title = filter_xss_admin($element['#title']);

  // NOTE: CHANGED LINE BELOW!
  // If there are attributes already, use them. If not, create empty array.
  $attributes = isset($element['#label_attributes'])?$element['#label_attributes']:array();

  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    $attributes['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    $attributes['class'] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // The leading whitespace helps visually separate fields from inline labels.
  return ' &lt;label' . drupal_attributes($attributes) . '&gt;' . $t('!title !required', array('!title' =&gt; $title, '!required' =&gt; $required)) . "&lt;/label&gt;\n";
}