Best Python code snippet using avocado_python
__init__.py
Source:__init__.py  
...140                using = _handle_control_tag_using(path, node.name, using, value[1])141            else:142                _handle_control_tag(path, node, value)143        elif isinstance(value[1], collections.OrderedDict):144            child = _tree_node_from_values(path,145                                           astring.to_text(value[0]),146                                           value[1],147                                           using)148            node.add_child(child)149        else:150            node.value[value[0]] = value[1]151    return using152def _node_content_from_dict(path, node, values, using):153    """Processes dict values into the current node content"""154    for key, value in values.items():155        if isinstance(key, mux.Control):156            if key.code == YAML_USING:157                using = _handle_control_tag_using(path, node.name, using, value)158            else:159                _handle_control_tag(path, node, [key, value])160        elif (isinstance(value, collections.OrderedDict) or161              value is None):162            node.add_child(_tree_node_from_values(path, key, value, using))163        else:164            node.value[key] = value165    return using166def _tree_node_from_values(path, name, values, using):167    """Create `name` node and add values"""168    # Initialize the node169    node = mux.MuxTreeNode(astring.to_text(name))170    if not values:171        return node172    using = ''173    # Fill the node content from parsed values174    if isinstance(values, dict):175        using = _node_content_from_dict(path, node, values, using)176    else:177        using = _node_content_from_node(path, node, values, using)178    # Prefix nodes if tag "!using" was used179    if using:180        node = _apply_using(name, using, node)181    return node182def _mapping_to_tree_loader(loader, node, looks_like_node=False):183    """Maps yaml mapping tag to TreeNode structure"""184    _value = []185    for key_node, value_node in node.value:186        # Allow only strings as dict keys187        if key_node.tag.startswith('!'):    # reflect tags everywhere188            key = loader.construct_object(key_node)189        else:190            key = loader.construct_scalar(key_node)191        # If we are to keep them, use following, but we lose the control192        # for both, nodes and dicts193        # key = loader.construct_object(key_node)194        if isinstance(key, mux.Control):195            looks_like_node = True196        value = loader.construct_object(value_node)197        if isinstance(value, ListOfNodeObjects):198            looks_like_node = True199        _value.append((key, value))200    if not looks_like_node:201        return collections.OrderedDict(_value)202    objects = ListOfNodeObjects()203    for name, values in _value:204        if isinstance(values, ListOfNodeObjects):   # New node from list205            objects.append(_tree_node_from_values(loader.path, name,206                                                  values, loader.using))207        elif values is None:            # Empty node208            objects.append(mux.MuxTreeNode(astring.to_text(name)))209        else:                           # Values210            objects.append((name, values))211    return objects212def _mux_loader(loader, node):213    """214    Special !mux loader which allows to tag node as 'multiplex = True'.215    """216    if not isinstance(node, yaml.ScalarNode):217        objects = _mapping_to_tree_loader(loader, node, looks_like_node=True)218    else:   # This means it's empty node. Don't call mapping_to_tree_loader219        objects = ListOfNodeObjects()220    objects.append((mux.Control(YAML_MUX), None))221    return objects222class _BaseLoader(SafeLoader):223    """224    YAML loader with additional features related to mux225    """226    SafeLoader.add_constructor(u'!include',227                               lambda *_: mux.Control(YAML_INCLUDE))228    SafeLoader.add_constructor(u'!using',229                               lambda *_: mux.Control(YAML_USING))230    SafeLoader.add_constructor(u'!remove_node',231                               lambda *_: mux.Control(YAML_REMOVE_NODE))232    SafeLoader.add_constructor(u'!remove_value',233                               lambda *_: mux.Control(YAML_REMOVE_VALUE))234    SafeLoader.add_constructor(u'!filter-only',235                               lambda *_: mux.Control(YAML_FILTER_ONLY))236    SafeLoader.add_constructor(u'!filter-out',237                               lambda *_: mux.Control(YAML_FILTER_OUT))238    SafeLoader.add_constructor(u'tag:yaml.org,2002:python/dict',239                               SafeLoader.construct_yaml_map)240    SafeLoader.add_constructor(u'!mux', _mux_loader)241    SafeLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,242                               _mapping_to_tree_loader)243def _create_from_yaml(path):244    """Create tree structure from yaml stream"""245    # Parse file name ([$using:]$path)246    path = __RE_FILE_SPLIT.split(path, 1)247    if len(path) == 1:248        path = __RE_FILE_SUBS.sub(':', path[0])249        using = ["run"]250    else:251        nodes = __RE_FILE_SUBS.sub(':', path[0]).strip('/').split('/')252        using = [node for node in nodes if node]253        if not path[0].startswith('/'):  # relative path, put into /run254            using.insert(0, 'run')255        path = __RE_FILE_SUBS.sub(':', path[1])256    # For loader instance needs different "path" and "using" values257    class Loader(_BaseLoader):258        _BaseLoader.path = path259        _BaseLoader.using = using260    # Load the tree261    with open(path) as stream:262        loaded_tree = yaml.load(stream, Loader)  # nosec263        if loaded_tree is None:264            return265        loaded_tree = _tree_node_from_values(path, '', loaded_tree, using)266    # Add prefix267    if using:268        loaded_tree.name = using.pop()269        while True:270            if not using:271                break272            loaded_tree = mux.MuxTreeNode(using.pop(), children=[loaded_tree])273        loaded_tree = mux.MuxTreeNode('', children=[loaded_tree])274    return loaded_tree275def create_from_yaml(paths):276    """Create tree structure from yaml-like file.277    :param paths: File object to be processed278    :raise SyntaxError: When yaml-file is corrupted279    :return: Root of the created tree structure...varianter_yaml_to_mux.py
Source:varianter_yaml_to_mux.py  
...139                using = _handle_control_tag_using(path, node.name, using, value[1])140            else:141                _handle_control_tag(path, node, value)142        elif isinstance(value[1], collections.OrderedDict):143            child = _tree_node_from_values(144                path, astring.to_text(value[0]), value[1], using145            )146            node.add_child(child)147        else:148            node.value[value[0]] = value[1]149    return using150def _node_content_from_dict(path, node, values, using):151    """Processes dict values into the current node content"""152    for key, value in values.items():153        if isinstance(key, mux.Control):154            if key.code == YAML_USING:155                using = _handle_control_tag_using(path, node.name, using, value)156            else:157                _handle_control_tag(path, node, [key, value])158        elif isinstance(value, collections.OrderedDict) or value is None:159            node.add_child(_tree_node_from_values(path, key, value, using))160        elif value == "null":161            node.value[key] = None162        else:163            node.value[key] = value164    return using165def _tree_node_from_values(path, name, values, using):166    """Create `name` node and add values"""167    # Initialize the node168    node = mux.MuxTreeNode(astring.to_text(name))169    if not values:170        return node171    using = ""172    # Fill the node content from parsed values173    if isinstance(values, dict):174        using = _node_content_from_dict(path, node, values, using)175    else:176        using = _node_content_from_node(path, node, values, using)177    # Prefix nodes if tag "!using" was used178    if using:179        node = _apply_using(name, using, node)180    return node181def _mapping_to_tree_loader(loader, node, looks_like_node=False):182    """Maps yaml mapping tag to TreeNode structure"""183    _value = []184    for key_node, value_node in node.value:185        # Allow only strings as dict keys186        if key_node.tag.startswith("!"):  # reflect tags everywhere187            key = loader.construct_object(key_node)188        else:189            key = loader.construct_scalar(key_node)190        # If we are to keep them, use following, but we lose the control191        # for both, nodes and dicts192        # key = loader.construct_object(key_node)193        if isinstance(key, mux.Control):194            looks_like_node = True195        value = loader.construct_object(value_node)196        if isinstance(value, ListOfNodeObjects):197            looks_like_node = True198        _value.append((key, value))199    if not looks_like_node:200        return collections.OrderedDict(_value)201    objects = ListOfNodeObjects()202    for name, values in _value:203        if isinstance(values, ListOfNodeObjects):  # New node from list204            objects.append(205                _tree_node_from_values(loader.path, name, values, loader.using)206            )207        elif values is None:  # Empty node208            objects.append(mux.MuxTreeNode(astring.to_text(name)))209        elif values == "null":210            objects.append((name, None))211        else:  # Values212            objects.append((name, values))213    return objects214def _mux_loader(loader, node):215    """216    Special !mux loader which allows to tag node as 'multiplex = True'.217    """218    if not isinstance(node, yaml.ScalarNode):219        objects = _mapping_to_tree_loader(loader, node, looks_like_node=True)220    else:  # This means it's empty node. Don't call mapping_to_tree_loader221        objects = ListOfNodeObjects()222    objects.append((mux.Control(YAML_MUX), None))223    return objects224class _BaseLoader(SafeLoader):225    """226    YAML loader with additional features related to mux227    """228    SafeLoader.add_constructor("!include", lambda *_: mux.Control(YAML_INCLUDE))229    SafeLoader.add_constructor("!using", lambda *_: mux.Control(YAML_USING))230    SafeLoader.add_constructor("!remove_node", lambda *_: mux.Control(YAML_REMOVE_NODE))231    SafeLoader.add_constructor(232        "!remove_value", lambda *_: mux.Control(YAML_REMOVE_VALUE)233    )234    SafeLoader.add_constructor("!filter-only", lambda *_: mux.Control(YAML_FILTER_ONLY))235    SafeLoader.add_constructor("!filter-out", lambda *_: mux.Control(YAML_FILTER_OUT))236    SafeLoader.add_constructor(237        "tag:yaml.org,2002:python/dict", SafeLoader.construct_yaml_map238    )239    SafeLoader.add_constructor("!mux", _mux_loader)240    SafeLoader.add_constructor(241        yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _mapping_to_tree_loader242    )243def _create_from_yaml(path):244    """Create tree structure from yaml stream"""245    # Parse file name ([$using:]$path)246    path = __RE_FILE_SPLIT.split(path, 1)247    if len(path) == 1:248        path = __RE_FILE_SUBS.sub(":", path[0])249        using = ["run"]250    else:251        nodes = __RE_FILE_SUBS.sub(":", path[0]).strip("/").split("/")252        using = [node for node in nodes if node]253        if not path[0].startswith("/"):  # relative path, put into /run254            using.insert(0, "run")255        path = __RE_FILE_SUBS.sub(":", path[1])256    # For loader instance needs different "path" and "using" values257    class Loader(_BaseLoader):258        _BaseLoader.path = path259        _BaseLoader.using = using260    # Load the tree261    with open(path, encoding="utf-8") as stream:262        loaded_tree = yaml.load(stream, Loader)  # nosec263        if loaded_tree is None:264            return265        loaded_tree = _tree_node_from_values(path, "", loaded_tree, using)266    # Add prefix267    if using:268        loaded_tree.name = using.pop()269        while True:270            if not using:271                break272            loaded_tree = mux.MuxTreeNode(using.pop(), children=[loaded_tree])273        loaded_tree = mux.MuxTreeNode("", children=[loaded_tree])274    return loaded_tree275def create_from_yaml(paths):276    """Create tree structure from yaml-like file.277    :param paths: File object to be processed278    :raise SyntaxError: When yaml-file is corrupted279    :return: Root of the created tree structure...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!!
