Parse a style definition. Args: style_definition (str): A string containing a style. Raises: errors.StyleSyntaxError: If the style definition syntax is invalid. Returns: `Style`: A Style instance.
(cls, style_definition: str)
| 496 | @classmethod |
| 497 | @lru_cache(maxsize=4096) |
| 498 | def parse(cls, style_definition: str) -> class="st">"Style": |
| 499 | class="st">"""Parse a style definition. |
| 500 | |
| 501 | Args: |
| 502 | style_definition (str): A string containing a style. |
| 503 | |
| 504 | Raises: |
| 505 | errors.StyleSyntaxError: If the style definition syntax is invalid. |
| 506 | |
| 507 | Returns: |
| 508 | `Style`: A Style instance. |
| 509 | class="st">""" |
| 510 | if style_definition.strip() == class="st">"none" or not style_definition: |
| 511 | return cls.null() |
| 512 | |
| 513 | STYLE_ATTRIBUTES = cls.STYLE_ATTRIBUTES |
| 514 | color: Optional[str] = None |
| 515 | bgcolor: Optional[str] = None |
| 516 | attributes: Dict[str, Optional[Any]] = {} |
| 517 | link: Optional[str] = None |
| 518 | |
| 519 | words = iter(style_definition.split()) |
| 520 | for original_word in words: |
| 521 | word = original_word.lower() |
| 522 | if word == class="st">"on": |
| 523 | word = next(words, class="st">"") |
| 524 | if not word: |
| 525 | raise errors.StyleSyntaxError(class="st">"color expected after &class="cm">#x27;on'") |
| 526 | try: |
| 527 | Color.parse(word) |
| 528 | except ColorParseError as error: |
| 529 | raise errors.StyleSyntaxError( |
| 530 | fclass="st">"unable to parse {word!r} as background color; {error}" |
| 531 | ) from None |
| 532 | bgcolor = word |
| 533 | |
| 534 | elif word == class="st">"not": |
| 535 | word = next(words, class="st">"") |
| 536 | attribute = STYLE_ATTRIBUTES.get(word) |
| 537 | if attribute is None: |
| 538 | raise errors.StyleSyntaxError( |
| 539 | fclass="st">"expected style attribute after &class="cm">#x27;not', found {word!r}" |
| 540 | ) |
| 541 | attributes[attribute] = False |
| 542 | |
| 543 | elif word == class="st">"link": |
| 544 | word = next(words, class="st">"") |
| 545 | if not word: |
| 546 | raise errors.StyleSyntaxError(class="st">"URL expected after &class="cm">#x27;link'") |
| 547 | link = word |
| 548 | |
| 549 | elif word in STYLE_ATTRIBUTES: |
| 550 | attributes[STYLE_ATTRIBUTES[word]] = True |
| 551 | |
| 552 | else: |
| 553 | try: |
| 554 | Color.parse(word) |
| 555 | except ColorParseError as error: |