Best Python code snippet using localstack_python
tmxreader.py
Source:tmxreader.py
...521 written in java. It can be found here: http://mapeditor.org/522 """523 def _build_tile_set(self, tile_set_node, world_map):524 tile_set = TileSet()525 self._set_attributes(tile_set_node, tile_set)526 if hasattr(tile_set, "source"):527 tile_set = self._parse_tsx(tile_set.source, tile_set, world_map)528 else:529 tile_set = self._get_tile_set(tile_set_node, tile_set, \530 self.map_file_name)531 world_map.tile_sets.append(tile_set)532 def _parse_tsx(self, file_name, tile_set, world_map):533 # ISSUE 5: the *.tsx file is probably relative to the *.tmx file534 if not os.path.isabs(file_name):535 # print "map file name", self.map_file_name536 file_name = self._get_abs_path(self.map_file_name, file_name)537 # print "tsx filename: ", file_name538 # would be more elegant to use "with open(file_name, "rb") as file:" 539 # but that is python 2.6540 file = None541 try:542 file = open(file_name, "rb")543 dom = minidom.parseString(file.read())544 finally:545 if file:546 file.close()547 for node in self._get_nodes(dom.childNodes, 'tileset'):548 tile_set = self._get_tile_set(node, tile_set, file_name)549 break550 return tile_set551 def _get_tile_set(self, tile_set_node, tile_set, base_path):552 for node in self._get_nodes(tile_set_node.childNodes, 'image'):553 self._build_tile_set_image(node, tile_set, base_path)554 for node in self._get_nodes(tile_set_node.childNodes, 'tile'):555 self._build_tile_set_tile(node, tile_set)556 self._set_attributes(tile_set_node, tile_set)557 return tile_set558 def _build_tile_set_image(self, image_node, tile_set, base_path):559 image = TileImage()560 self._set_attributes(image_node, image)561 # id of TileImage has to be set! -> Tile.TileImage will only have id set562 for node in self._get_nodes(image_node.childNodes, 'data'):563 self._set_attributes(node, image)564 image.content = node.childNodes[0].nodeValue565 image.source = self._get_abs_path(base_path, image.source) # ISSUE 5566 tile_set.images.append(image)567 def _get_abs_path(self, base, relative):568 if os.path.isabs(relative):569 return relative570 if os.path.isfile(base):571 base = os.path.dirname(base)572 return os.path.abspath(os.path.join(base, relative))573 def _build_tile_set_tile(self, tile_set_node, tile_set):574 tile = Tile()575 self._set_attributes(tile_set_node, tile)576 for node in self._get_nodes(tile_set_node.childNodes, 'image'):577 self._build_tile_set_tile_image(node, tile)578 tile_set.tiles.append(tile)579 def _build_tile_set_tile_image(self, tile_node, tile):580 tile_image = TileImage()581 self._set_attributes(tile_node, tile_image)582 for node in self._get_nodes(tile_node.childNodes, 'data'):583 self._set_attributes(node, tile_image)584 tile_image.content = node.childNodes[0].nodeValue585 tile.images.append(tile_image)586 def _build_layer(self, layer_node, world_map):587 layer = TileLayer()588 self._set_attributes(layer_node, layer)589 for node in self._get_nodes(layer_node.childNodes, 'data'):590 self._set_attributes(node, layer)591 if layer.encoding:592 layer.encoded_content = node.lastChild.nodeValue593 else:594 #print 'has childnodes', node.hasChildNodes()595 layer.encoded_content = []596 for child in node.childNodes:597 if child.nodeType == Node.ELEMENT_NODE and \598 child.nodeName == "tile":599 val = child.attributes["gid"].nodeValue600 #print child, val601 layer.encoded_content.append(val)602 world_map.layers.append(layer)603 def _build_world_map(self, world_node):604 world_map = TileMap()605 self._set_attributes(world_node, world_map)606 for node in self._get_nodes(world_node.childNodes, 'tileset'):607 self._build_tile_set(node, world_map)608 for node in self._get_nodes(world_node.childNodes, 'layer'):609 self._build_layer(node, world_map)610 for node in self._get_nodes(world_node.childNodes, 'objectgroup'):611 self._build_object_groups(node, world_map)612 return world_map613 def _build_object_groups(self, object_group_node, world_map):614 object_group = MapObjectGroupLayer()615 self._set_attributes(object_group_node, object_group)616 for node in self._get_nodes(object_group_node.childNodes, 'object'):617 tiled_object = MapObject()618 self._set_attributes(node, tiled_object)619 for img_node in self._get_nodes(node.childNodes, 'image'):620 tiled_object.image_source = \621 img_node.attributes['source'].nodeValue622 object_group.objects.append(tiled_object)623 # ISSUE 9624 world_map.layers.append(object_group)625 # -- helpers -- #626 def _get_nodes(self, nodes, name):627 for node in nodes:628 if node.nodeType == Node.ELEMENT_NODE and node.nodeName == name:629 yield node630 def _set_attributes(self, node, obj):631 attrs = node.attributes632 for attr_name in list(attrs.keys()):633 setattr(obj, attr_name, attrs.get(attr_name).nodeValue)634 self._get_properties(node, obj)635 def _get_properties(self, node, obj):636 props = {}637 for properties_node in self._get_nodes(node.childNodes, 'properties'):638 for property_node in self._get_nodes(properties_node.childNodes, 'property'):639 try:640 props[property_node.attributes['name'].nodeValue] = \641 property_node.attributes['value'].nodeValue642 except KeyError:643 props[property_node.attributes['name'].nodeValue] = \644 property_node.lastChild.nodeValue...
style.py
Source:style.py
1import sys2from functools import lru_cache3from marshal import loads, dumps4from random import randint5from typing import Any, cast, Dict, Iterable, List, Optional, Type, Union6from . import errors7from .color import Color, ColorParseError, ColorSystem, blend_rgb8from .repr import rich_repr, Result9from .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme10# Style instances and style definitions are often interchangeable11StyleType = Union[str, "Style"]12class _Bit:13 """A descriptor to get/set a style attribute bit."""14 __slots__ = ["bit"]15 def __init__(self, bit_no: int) -> None:16 self.bit = 1 << bit_no17 def __get__(self, obj: "Style", objtype: Type["Style"]) -> Optional[bool]:18 if obj._set_attributes & self.bit:19 return obj._attributes & self.bit != 020 return None21@rich_repr22class Style:23 """A terminal style.24 A terminal style consists of a color (`color`), a background color (`bgcolor`), and a number of attributes, such25 as bold, italic etc. The attributes have 3 states: they can either be on26 (``True``), off (``False``), or not set (``None``).27 Args:28 color (Union[Color, str], optional): Color of terminal text. Defaults to None.29 bgcolor (Union[Color, str], optional): Color of terminal background. Defaults to None.30 bold (bool, optional): Enable bold text. Defaults to None.31 dim (bool, optional): Enable dim text. Defaults to None.32 italic (bool, optional): Enable italic text. Defaults to None.33 underline (bool, optional): Enable underlined text. Defaults to None.34 blink (bool, optional): Enabled blinking text. Defaults to None.35 blink2 (bool, optional): Enable fast blinking text. Defaults to None.36 reverse (bool, optional): Enabled reverse text. Defaults to None.37 conceal (bool, optional): Enable concealed text. Defaults to None.38 strike (bool, optional): Enable strikethrough text. Defaults to None.39 underline2 (bool, optional): Enable doubly underlined text. Defaults to None.40 frame (bool, optional): Enable framed text. Defaults to None.41 encircle (bool, optional): Enable encircled text. Defaults to None.42 overline (bool, optional): Enable overlined text. Defaults to None.43 link (str, link): Link URL. Defaults to None.44 """45 _color: Optional[Color]46 _bgcolor: Optional[Color]47 _attributes: int48 _set_attributes: int49 _hash: int50 _null: bool51 _meta: Optional[bytes]52 __slots__ = [53 "_color",54 "_bgcolor",55 "_attributes",56 "_set_attributes",57 "_link",58 "_link_id",59 "_ansi",60 "_style_definition",61 "_hash",62 "_null",63 "_meta",64 ]65 # maps bits on to SGR parameter66 _style_map = {67 0: "1",68 1: "2",69 2: "3",70 3: "4",71 4: "5",72 5: "6",73 6: "7",74 7: "8",75 8: "9",76 9: "21",77 10: "51",78 11: "52",79 12: "53",80 }81 STYLE_ATTRIBUTES = {82 "dim": "dim",83 "d": "dim",84 "bold": "bold",85 "b": "bold",86 "italic": "italic",87 "i": "italic",88 "underline": "underline",89 "u": "underline",90 "blink": "blink",91 "blink2": "blink2",92 "reverse": "reverse",93 "r": "reverse",94 "conceal": "conceal",95 "c": "conceal",96 "strike": "strike",97 "s": "strike",98 "underline2": "underline2",99 "uu": "underline2",100 "frame": "frame",101 "encircle": "encircle",102 "overline": "overline",103 "o": "overline",104 }105 def __init__(106 self,107 *,108 color: Optional[Union[Color, str]] = None,109 bgcolor: Optional[Union[Color, str]] = None,110 bold: Optional[bool] = None,111 dim: Optional[bool] = None,112 italic: Optional[bool] = None,113 underline: Optional[bool] = None,114 blink: Optional[bool] = None,115 blink2: Optional[bool] = None,116 reverse: Optional[bool] = None,117 conceal: Optional[bool] = None,118 strike: Optional[bool] = None,119 underline2: Optional[bool] = None,120 frame: Optional[bool] = None,121 encircle: Optional[bool] = None,122 overline: Optional[bool] = None,123 link: Optional[str] = None,124 meta: Optional[Dict[str, Any]] = None,125 ):126 self._ansi: Optional[str] = None127 self._style_definition: Optional[str] = None128 def _make_color(color: Union[Color, str]) -> Color:129 return color if isinstance(color, Color) else Color.parse(color)130 self._color = None if color is None else _make_color(color)131 self._bgcolor = None if bgcolor is None else _make_color(bgcolor)132 self._set_attributes = sum(133 (134 bold is not None,135 dim is not None and 2,136 italic is not None and 4,137 underline is not None and 8,138 blink is not None and 16,139 blink2 is not None and 32,140 reverse is not None and 64,141 conceal is not None and 128,142 strike is not None and 256,143 underline2 is not None and 512,144 frame is not None and 1024,145 encircle is not None and 2048,146 overline is not None and 4096,147 )148 )149 self._attributes = (150 sum(151 (152 bold and 1 or 0,153 dim and 2 or 0,154 italic and 4 or 0,155 underline and 8 or 0,156 blink and 16 or 0,157 blink2 and 32 or 0,158 reverse and 64 or 0,159 conceal and 128 or 0,160 strike and 256 or 0,161 underline2 and 512 or 0,162 frame and 1024 or 0,163 encircle and 2048 or 0,164 overline and 4096 or 0,165 )166 )167 if self._set_attributes168 else 0169 )170 self._link = link171 self._link_id = f"{randint(0, 999999)}" if link else ""172 self._meta = None if meta is None else dumps(meta)173 self._hash = hash(174 (175 self._color,176 self._bgcolor,177 self._attributes,178 self._set_attributes,179 link,180 self._meta,181 )182 )183 self._null = not (self._set_attributes or color or bgcolor or link or meta)184 @classmethod185 def null(cls) -> "Style":186 """Create an 'null' style, equivalent to Style(), but more performant."""187 return NULL_STYLE188 @classmethod189 def from_color(190 cls, color: Optional[Color] = None, bgcolor: Optional[Color] = None191 ) -> "Style":192 """Create a new style with colors and no attributes.193 Returns:194 color (Optional[Color]): A (foreground) color, or None for no color. Defaults to None.195 bgcolor (Optional[Color]): A (background) color, or None for no color. Defaults to None.196 """197 style: Style = cls.__new__(Style)198 style._ansi = None199 style._style_definition = None200 style._color = color201 style._bgcolor = bgcolor202 style._set_attributes = 0203 style._attributes = 0204 style._link = None205 style._link_id = ""206 style._meta = None207 style._hash = hash(208 (209 color,210 bgcolor,211 None,212 None,213 None,214 None,215 )216 )217 style._null = not (color or bgcolor)218 return style219 @classmethod220 def from_meta(cls, meta: Optional[Dict[str, Any]]) -> "Style":221 """Create a new style with meta data.222 Returns:223 meta (Optional[Dict[str, Any]]): A dictionary of meta data. Defaults to None.224 """225 style: Style = cls.__new__(Style)226 style._ansi = None227 style._style_definition = None228 style._color = None229 style._bgcolor = None230 style._set_attributes = 0231 style._attributes = 0232 style._link = None233 style._link_id = ""234 style._meta = dumps(meta)235 style._hash = hash(236 (237 None,238 None,239 None,240 None,241 None,242 style._meta,243 )244 )245 style._null = not (meta)246 return style247 @classmethod248 def on(cls, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Style":249 """Create a blank style with meta information.250 Example:251 style = Style.on(click=self.on_click)252 Args:253 meta (Optiona[Dict[str, Any]], optional): An optional dict of meta information.254 **handlers (Any): Keyword arguments are translated in to handlers.255 Returns:256 Style: A Style with meta information attached.257 """258 meta = {} if meta is None else meta259 meta.update({f"@{key}": value for key, value in handlers.items()})260 return cls.from_meta(meta)261 bold = _Bit(0)262 dim = _Bit(1)263 italic = _Bit(2)264 underline = _Bit(3)265 blink = _Bit(4)266 blink2 = _Bit(5)267 reverse = _Bit(6)268 conceal = _Bit(7)269 strike = _Bit(8)270 underline2 = _Bit(9)271 frame = _Bit(10)272 encircle = _Bit(11)273 overline = _Bit(12)274 @property275 def link_id(self) -> str:276 """Get a link id, used in ansi code for links."""277 return self._link_id278 def __str__(self) -> str:279 """Re-generate style definition from attributes."""280 if self._style_definition is None:281 attributes: List[str] = []282 append = attributes.append283 bits = self._set_attributes284 if bits & 0b0000000001111:285 if bits & 1:286 append("bold" if self.bold else "not bold")287 if bits & (1 << 1):288 append("dim" if self.dim else "not dim")289 if bits & (1 << 2):290 append("italic" if self.italic else "not italic")291 if bits & (1 << 3):292 append("underline" if self.underline else "not underline")293 if bits & 0b0000111110000:294 if bits & (1 << 4):295 append("blink" if self.blink else "not blink")296 if bits & (1 << 5):297 append("blink2" if self.blink2 else "not blink2")298 if bits & (1 << 6):299 append("reverse" if self.reverse else "not reverse")300 if bits & (1 << 7):301 append("conceal" if self.conceal else "not conceal")302 if bits & (1 << 8):303 append("strike" if self.strike else "not strike")304 if bits & 0b1111000000000:305 if bits & (1 << 9):306 append("underline2" if self.underline2 else "not underline2")307 if bits & (1 << 10):308 append("frame" if self.frame else "not frame")309 if bits & (1 << 11):310 append("encircle" if self.encircle else "not encircle")311 if bits & (1 << 12):312 append("overline" if self.overline else "not overline")313 if self._color is not None:314 append(self._color.name)315 if self._bgcolor is not None:316 append("on")317 append(self._bgcolor.name)318 if self._link:319 append("link")320 append(self._link)321 self._style_definition = " ".join(attributes) or "none"322 return self._style_definition323 def __bool__(self) -> bool:324 """A Style is false if it has no attributes, colors, or links."""325 return not self._null326 def _make_ansi_codes(self, color_system: ColorSystem) -> str:327 """Generate ANSI codes for this style.328 Args:329 color_system (ColorSystem): Color system.330 Returns:331 str: String containing codes.332 """333 if self._ansi is None:334 sgr: List[str] = []335 append = sgr.append336 _style_map = self._style_map337 attributes = self._attributes & self._set_attributes338 if attributes:339 if attributes & 1:340 append(_style_map[0])341 if attributes & 2:342 append(_style_map[1])343 if attributes & 4:344 append(_style_map[2])345 if attributes & 8:346 append(_style_map[3])347 if attributes & 0b0000111110000:348 for bit in range(4, 9):349 if attributes & (1 << bit):350 append(_style_map[bit])351 if attributes & 0b1111000000000:352 for bit in range(9, 13):353 if attributes & (1 << bit):354 append(_style_map[bit])355 if self._color is not None:356 sgr.extend(self._color.downgrade(color_system).get_ansi_codes())357 if self._bgcolor is not None:358 sgr.extend(359 self._bgcolor.downgrade(color_system).get_ansi_codes(360 foreground=False361 )362 )363 self._ansi = ";".join(sgr)364 return self._ansi365 @classmethod366 @lru_cache(maxsize=1024)367 def normalize(cls, style: str) -> str:368 """Normalize a style definition so that styles with the same effect have the same string369 representation.370 Args:371 style (str): A style definition.372 Returns:373 str: Normal form of style definition.374 """375 try:376 return str(cls.parse(style))377 except errors.StyleSyntaxError:378 return style.strip().lower()379 @classmethod380 def pick_first(cls, *values: Optional[StyleType]) -> StyleType:381 """Pick first non-None style."""382 for value in values:383 if value is not None:384 return value385 raise ValueError("expected at least one non-None style")386 def __rich_repr__(self) -> Result:387 yield "color", self.color, None388 yield "bgcolor", self.bgcolor, None389 yield "bold", self.bold, None,390 yield "dim", self.dim, None,391 yield "italic", self.italic, None392 yield "underline", self.underline, None,393 yield "blink", self.blink, None394 yield "blink2", self.blink2, None395 yield "reverse", self.reverse, None396 yield "conceal", self.conceal, None397 yield "strike", self.strike, None398 yield "underline2", self.underline2, None399 yield "frame", self.frame, None400 yield "encircle", self.encircle, None401 yield "link", self.link, None402 if self._meta:403 yield "meta", self.meta404 def __eq__(self, other: Any) -> bool:405 if not isinstance(other, Style):406 return NotImplemented407 return (408 self._color == other._color409 and self._bgcolor == other._bgcolor410 and self._set_attributes == other._set_attributes411 and self._attributes == other._attributes412 and self._link == other._link413 and self._meta == other._meta414 )415 def __hash__(self) -> int:416 return self._hash417 @property418 def color(self) -> Optional[Color]:419 """The foreground color or None if it is not set."""420 return self._color421 @property422 def bgcolor(self) -> Optional[Color]:423 """The background color or None if it is not set."""424 return self._bgcolor425 @property426 def link(self) -> Optional[str]:427 """Link text, if set."""428 return self._link429 @property430 def transparent_background(self) -> bool:431 """Check if the style specified a transparent background."""432 return self.bgcolor is None or self.bgcolor.is_default433 @property434 def background_style(self) -> "Style":435 """A Style with background only."""436 return Style(bgcolor=self.bgcolor)437 @property438 def meta(self) -> Dict[str, Any]:439 """Get meta information (can not be changed after construction)."""440 return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))441 @property442 def without_color(self) -> "Style":443 """Get a copy of the style with color removed."""444 if self._null:445 return NULL_STYLE446 style: Style = self.__new__(Style)447 style._ansi = None448 style._style_definition = None449 style._color = None450 style._bgcolor = None451 style._attributes = self._attributes452 style._set_attributes = self._set_attributes453 style._link = self._link454 style._link_id = f"{randint(0, 999999)}" if self._link else ""455 style._hash = self._hash456 style._null = False457 style._meta = None458 return style459 @classmethod460 @lru_cache(maxsize=4096)461 def parse(cls, style_definition: str) -> "Style":462 """Parse a style definition.463 Args:464 style_definition (str): A string containing a style.465 Raises:466 errors.StyleSyntaxError: If the style definition syntax is invalid.467 Returns:468 `Style`: A Style instance.469 """470 if style_definition.strip() == "none" or not style_definition:471 return cls.null()472 STYLE_ATTRIBUTES = cls.STYLE_ATTRIBUTES473 color: Optional[str] = None474 bgcolor: Optional[str] = None475 attributes: Dict[str, Optional[Any]] = {}476 link: Optional[str] = None477 words = iter(style_definition.split())478 for original_word in words:479 word = original_word.lower()480 if word == "on":481 word = next(words, "")482 if not word:483 raise errors.StyleSyntaxError("color expected after 'on'")484 try:485 Color.parse(word) is None486 except ColorParseError as error:487 raise errors.StyleSyntaxError(488 f"unable to parse {word!r} as background color; {error}"489 ) from None490 bgcolor = word491 elif word == "not":492 word = next(words, "")493 attribute = STYLE_ATTRIBUTES.get(word)494 if attribute is None:495 raise errors.StyleSyntaxError(496 f"expected style attribute after 'not', found {word!r}"497 )498 attributes[attribute] = False499 elif word == "link":500 word = next(words, "")501 if not word:502 raise errors.StyleSyntaxError("URL expected after 'link'")503 link = word504 elif word in STYLE_ATTRIBUTES:505 attributes[STYLE_ATTRIBUTES[word]] = True506 else:507 try:508 Color.parse(word)509 except ColorParseError as error:510 raise errors.StyleSyntaxError(511 f"unable to parse {word!r} as color; {error}"512 ) from None513 color = word514 style = Style(color=color, bgcolor=bgcolor, link=link, **attributes)515 return style516 @lru_cache(maxsize=1024)517 def get_html_style(self, theme: Optional[TerminalTheme] = None) -> str:518 """Get a CSS style rule."""519 theme = theme or DEFAULT_TERMINAL_THEME520 css: List[str] = []521 append = css.append522 color = self.color523 bgcolor = self.bgcolor524 if self.reverse:525 color, bgcolor = bgcolor, color526 if self.dim:527 foreground_color = (528 theme.foreground_color if color is None else color.get_truecolor(theme)529 )530 color = Color.from_triplet(531 blend_rgb(foreground_color, theme.background_color, 0.5)532 )533 if color is not None:534 theme_color = color.get_truecolor(theme)535 append(f"color: {theme_color.hex}")536 append(f"text-decoration-color: {theme_color.hex}")537 if bgcolor is not None:538 theme_color = bgcolor.get_truecolor(theme, foreground=False)539 append(f"background-color: {theme_color.hex}")540 if self.bold:541 append("font-weight: bold")542 if self.italic:543 append("font-style: italic")544 if self.underline:545 append("text-decoration: underline")546 if self.strike:547 append("text-decoration: line-through")548 if self.overline:549 append("text-decoration: overline")550 return "; ".join(css)551 @classmethod552 def combine(cls, styles: Iterable["Style"]) -> "Style":553 """Combine styles and get result.554 Args:555 styles (Iterable[Style]): Styles to combine.556 Returns:557 Style: A new style instance.558 """559 iter_styles = iter(styles)560 return sum(iter_styles, next(iter_styles))561 @classmethod562 def chain(cls, *styles: "Style") -> "Style":563 """Combine styles from positional argument in to a single style.564 Args:565 *styles (Iterable[Style]): Styles to combine.566 Returns:567 Style: A new style instance.568 """569 iter_styles = iter(styles)570 return sum(iter_styles, next(iter_styles))571 def copy(self) -> "Style":572 """Get a copy of this style.573 Returns:574 Style: A new Style instance with identical attributes.575 """576 if self._null:577 return NULL_STYLE578 style: Style = self.__new__(Style)579 style._ansi = self._ansi580 style._style_definition = self._style_definition581 style._color = self._color582 style._bgcolor = self._bgcolor583 style._attributes = self._attributes584 style._set_attributes = self._set_attributes585 style._link = self._link586 style._link_id = f"{randint(0, 999999)}" if self._link else ""587 style._hash = self._hash588 style._null = False589 style._meta = self._meta590 return style591 def update_link(self, link: Optional[str] = None) -> "Style":592 """Get a copy with a different value for link.593 Args:594 link (str, optional): New value for link. Defaults to None.595 Returns:596 Style: A new Style instance.597 """598 style: Style = self.__new__(Style)599 style._ansi = self._ansi600 style._style_definition = self._style_definition601 style._color = self._color602 style._bgcolor = self._bgcolor603 style._attributes = self._attributes604 style._set_attributes = self._set_attributes605 style._link = link606 style._link_id = f"{randint(0, 999999)}" if link else ""607 style._hash = self._hash608 style._null = False609 style._meta = self._meta610 return style611 def render(612 self,613 text: str = "",614 *,615 color_system: Optional[ColorSystem] = ColorSystem.TRUECOLOR,616 legacy_windows: bool = False,617 ) -> str:618 """Render the ANSI codes for the style.619 Args:620 text (str, optional): A string to style. Defaults to "".621 color_system (Optional[ColorSystem], optional): Color system to render to. Defaults to ColorSystem.TRUECOLOR.622 Returns:623 str: A string containing ANSI style codes.624 """625 if not text or color_system is None:626 return text627 attrs = self._make_ansi_codes(color_system)628 rendered = f"\x1b[{attrs}m{text}\x1b[0m" if attrs else text629 if self._link and not legacy_windows:630 rendered = (631 f"\x1b]8;id={self._link_id};{self._link}\x1b\\{rendered}\x1b]8;;\x1b\\"632 )633 return rendered634 def test(self, text: Optional[str] = None) -> None:635 """Write text with style directly to terminal.636 This method is for testing purposes only.637 Args:638 text (Optional[str], optional): Text to style or None for style name.639 """640 text = text or str(self)641 sys.stdout.write(f"{self.render(text)}\n")642 def __add__(self, style: Optional["Style"]) -> "Style":643 if not (isinstance(style, Style) or style is None):644 return NotImplemented645 if style is None or style._null:646 return self647 if self._null:648 return style649 new_style: Style = self.__new__(Style)650 new_style._ansi = None651 new_style._style_definition = None652 new_style._color = style._color or self._color653 new_style._bgcolor = style._bgcolor or self._bgcolor654 new_style._attributes = (self._attributes & ~style._set_attributes) | (655 style._attributes & style._set_attributes656 )657 new_style._set_attributes = self._set_attributes | style._set_attributes658 new_style._link = style._link or self._link659 new_style._link_id = style._link_id or self._link_id660 new_style._hash = style._hash661 new_style._null = self._null or style._null662 if self._meta and style._meta:663 new_style._meta = dumps({**self.meta, **style.meta})664 else:665 new_style._meta = self._meta or style._meta666 return new_style667NULL_STYLE = Style()668class StyleStack:669 """A stack of styles."""670 __slots__ = ["_stack"]671 def __init__(self, default_style: "Style") -> None:672 self._stack: List[Style] = [default_style]673 def __repr__(self) -> str:674 return f"<stylestack {self._stack!r}>"675 @property676 def current(self) -> Style:677 """Get the Style at the top of the stack."""678 return self._stack[-1]679 def push(self, style: Style) -> None:680 """Push a new style on to the stack.681 Args:682 style (Style): New style to combine with current style.683 """684 self._stack.append(self._stack[-1] + style)685 def pop(self) -> Style:686 """Pop last style and discard.687 Returns:688 Style: New current style (also available as stack.current)689 """690 self._stack.pop()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!