MCPcopy Index your code
hub / github.com/python-openxml/python-docx / ZeroOrOneChoice

Class ZeroOrOneChoice

src/docx/oxml/xmlchemy.py:583–639  ·  view source on GitHub ↗

Correspondes to an ``EG_*`` element group where at most one of its members may appear as a child.

Source from the content-addressed store, hash-verified

581
582
583class ZeroOrOneChoice(_BaseChildElement):
584 """Correspondes to an ``EG_*`` element group where at most one of its members may
585 appear as a child."""
586
587 def __init__(self, choices: Sequence[Choice], successors: tuple[str, ...] = ()):
588 self._choices = choices
589 self._successors = successors
590
591 def populate_class_members(self, element_cls: MetaOxmlElement, prop_name: str) -> None:
592 """Add the appropriate methods to `element_cls`."""
593 super(ZeroOrOneChoice, self).populate_class_members(element_cls, prop_name)
594 self._add_choice_getter()
595 for choice in self._choices:
596 choice.populate_class_members(element_cls, self._prop_name, self._successors)
597 self._add_group_remover()
598
599 def _add_choice_getter(self):
600 """Add a read-only ``{prop_name}`` property to the element class that returns
601 the present member of this group, or |None| if none are present."""
602 property_ = property(self._choice_getter, None, None)
603 # assign unconditionally to overwrite element name definition
604 setattr(self._element_cls, self._prop_name, property_)
605
606 def _add_group_remover(self):
607 """Add a ``_remove_eg_x()`` method to the element class for this choice
608 group."""
609
610 def _remove_choice_group(obj: BaseOxmlElement):
611 for tagname in self._member_nsptagnames:
612 obj.remove_all(tagname)
613
614 _remove_choice_group.__doc__ = "Remove the current choice group child element if present."
615 self._add_to_class(self._remove_choice_group_method_name, _remove_choice_group)
616
617 @property
618 def _choice_getter(self):
619 """Return a function object suitable for the "get" side of the property
620 descriptor."""
621
622 def get_group_member_element(obj: BaseOxmlElement):
623 return obj.first_child_found_in(*self._member_nsptagnames)
624
625 get_group_member_element.__doc__ = (
626 "Return the child element belonging to this element group, or "
627 "|None| if no member child is present."
628 )
629 return get_group_member_element
630
631 @lazyproperty
632 def _member_nsptagnames(self):
633 """Sequence of namespace-prefixed tagnames, one for each of the member elements
634 of this choice group."""
635 return [choice.nsptagname for choice in self._choices]
636
637 @lazyproperty
638 def _remove_choice_group_method_name(self):
639 return "_remove_%s" % self._prop_name
640

Callers 1

CT_ParentClass · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…