Python inspect.cleandoc() Examples

The following are 30 code examples of inspect.cleandoc(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inspect , or try the search function .
Example #1
Source File: ast3.py    From python-netsurv with MIT License 7 votes vote down vote up
def get_docstring(node, clean=True):
    """
    Return the docstring for the given node or None if no docstring can
    be found.  If the node provided does not have docstrings a TypeError
    will be raised.
    """
    if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
        raise TypeError("%r can't have docstrings" % node.__class__.__name__)
    if not(node.body and isinstance(node.body[0], Expr)):
        return
    node = node.body[0].value
    if isinstance(node, Str):
        text = node.s
    elif isinstance(node, Constant) and isinstance(node.value, str):
        text = node.value
    else:
        return
    if clean:
        import inspect
        text = inspect.cleandoc(text)
    return text 
Example #2
Source File: base.py    From tick with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def find_documented_attributes(class_name, attrs):
        """Parse the documentation to retrieve all attributes that have been
        documented and their documentation
        """
        # If a class is not documented we return an empty list
        if '__doc__' not in attrs:
            return []

        current_class_doc = inspect.cleandoc(attrs['__doc__'])
        parsed_doc = docscrape.ClassDoc(None, doc=current_class_doc)
        attr_docs = parsed_doc['Parameters'] + parsed_doc['Attributes'] + \
            parsed_doc['Other Parameters']

        attr_and_doc = []

        create_property_doc = BaseMeta.create_property_doc
        for attr_doc in attr_docs:
            attr_name = attr_doc[0]
            if ':' in attr_name:
                raise ValueError("Attribute '%s' has not a proper "
                                 "documentation, a space might be missing "
                                 "before colon" % attr_name)
            attr_and_doc += [(attr_name,
                              create_property_doc(class_name, attr_doc))]
        return attr_and_doc 
Example #3
Source File: ast3.py    From python-netsurv with MIT License 6 votes vote down vote up
def get_docstring(node, clean=True):
    """
    Return the docstring for the given node or None if no docstring can
    be found.  If the node provided does not have docstrings a TypeError
    will be raised.
    """
    if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
        raise TypeError("%r can't have docstrings" % node.__class__.__name__)
    if not(node.body and isinstance(node.body[0], Expr)):
        return
    node = node.body[0].value
    if isinstance(node, Str):
        text = node.s
    elif isinstance(node, Constant) and isinstance(node.value, str):
        text = node.value
    else:
        return
    if clean:
        import inspect
        text = inspect.cleandoc(text)
    return text 
Example #4
Source File: _pydev_calltip_util.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def create_function_stub(fn_name, fn_argspec, fn_docstring, indent=0):
    def shift_right(string, prefix):
        return ''.join(prefix + line for line in string.splitlines(True))

    fn_docstring = shift_right(inspect.cleandoc(fn_docstring), "  " * (indent + 1))
    ret = '''
def %s%s:
    """%s"""
    pass
''' % (fn_name, fn_argspec, fn_docstring)
    ret = ret[1:]  # remove first /n
    ret = ret.replace('\t', "  ")
    if indent:
        prefix = "  " * indent
        ret = shift_right(ret, prefix)
    return ret 
Example #5
Source File: gacha.py    From yui with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_full_help(self, prefix: str):
        return inspect.cleandoc(
            f"""
*가챠 계산기*

해로운 문명, 가챠에 관련된 계산을 도와줍니다.

`{prefix}가챠 수집 10` (총 10종을 모두 수집하려면 얼마나 구입해야하는지 계산)
`{prefix}가챠 수집 10/20` (총 20종 중에 10종을 수집하려면 얼마나 구입해야하는지 계산)
`{prefix}가챠 수집 전체 20종류중에 10종류` (위와 동일한 주문을 한국어 표현식으로도 가능합니다.)
`{prefix}가챠 도전 5%` (5% 확률요소의 성공을 위해 필요한 도전 횟수를 계산)
`{prefix}가챠 도전 0.1` (10%(`0.1`) 확률요소의 성공을 위해 필요한 도전 횟수를 계산)
`{prefix}가챠 도전 --성공 10 3%` (3% 확률요소의 10회 성공을 위해 필요한 도전 횟수를 계산)

Aliases

- `수집`대신 `collect`를 사용할 수 있습니다.
- `도전`대신 `challenge`를 사용할 수 있습니다.
- `도전`에서 `--성공`대신 `--성공횟수`/`--successes`/`-s`를 사용할 수 있습니다.
"""
        ) 
Example #6
Source File: decorators.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def _make_command(f, name, attrs, cls):
    if isinstance(f, Command):
        raise TypeError('Attempted to convert a callback into a '
                        'command twice.')
    try:
        params = f.__click_params__
        params.reverse()
        del f.__click_params__
    except AttributeError:
        params = []
    help = attrs.get('help')
    if help is None:
        help = inspect.getdoc(f)
        if isinstance(help, bytes):
            help = help.decode('utf-8')
    else:
        help = inspect.cleandoc(help)
    attrs['help'] = help
    _check_for_unicode_literals()
    return cls(name=name or f.__name__.lower(),
               callback=f, params=params, **attrs) 
Example #7
Source File: decorators.py    From pcocc with GNU General Public License v3.0 6 votes vote down vote up
def option(*param_decls, **attrs):
    """Attaches an option to the command.  All positional arguments are
    passed as parameter declarations to :class:`Option`; all keyword
    arguments are forwarded unchanged (except ``cls``).
    This is equivalent to creating an :class:`Option` instance manually
    and attaching it to the :attr:`Command.params` list.

    :param cls: the option class to instantiate.  This defaults to
                :class:`Option`.
    """
    def decorator(f):
        if 'help' in attrs:
            attrs['help'] = inspect.cleandoc(attrs['help'])
        OptionClass = attrs.pop('cls', Option)
        _param_memo(f, OptionClass(param_decls, **attrs))
        return f
    return decorator 
Example #8
Source File: decorators.py    From pcocc with GNU General Public License v3.0 6 votes vote down vote up
def _make_command(f, name, attrs, cls):
    if isinstance(f, Command):
        raise TypeError('Attempted to convert a callback into a '
                        'command twice.')
    try:
        params = f.__click_params__
        params.reverse()
        del f.__click_params__
    except AttributeError:
        params = []
    help = attrs.get('help')
    if help is None:
        help = inspect.getdoc(f)
        if isinstance(help, bytes):
            help = help.decode('utf-8')
    else:
        help = inspect.cleandoc(help)
    attrs['help'] = help
    return cls(name=name or f.__name__.lower(),
               callback=f, params=params, **attrs) 
Example #9
Source File: commands.py    From yui with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_full_help(self, prefix: str):
        return inspect.cleandoc(
            f"""
        *RSS Feed 구독*

        채널에서 RSS를 구독할 때 사용됩니다.
        구독하기로 한 주소에서 1분 간격으로 새 글을 찾습니다.

        `{prefix}rss add URL` (URL을 해당 채널에서 구독합니다)
        `{prefix}rss list` (해당 채널에서 구독중인 RSS Feed 목록을 가져옵니다)
        `{prefix}rss del ID` (고유번호가 ID인 RSS 구독을 중지합니다)

        `add` 대신 `추가` 를 사용할 수 있습니다.
        `list` 대신 `목록` 을 사용할 수 있습니다.
        `del` 대신 `delete`, `삭제`, `제거` 를 사용할 수 있습니다."""
        ) 
Example #10
Source File: decorators.py    From jbox with MIT License 6 votes vote down vote up
def option(*param_decls, **attrs):
    """Attaches an option to the command.  All positional arguments are
    passed as parameter declarations to :class:`Option`; all keyword
    arguments are forwarded unchanged (except ``cls``).
    This is equivalent to creating an :class:`Option` instance manually
    and attaching it to the :attr:`Command.params` list.

    :param cls: the option class to instantiate.  This defaults to
                :class:`Option`.
    """
    def decorator(f):
        if 'help' in attrs:
            attrs['help'] = inspect.cleandoc(attrs['help'])
        OptionClass = attrs.pop('cls', Option)
        _param_memo(f, OptionClass(param_decls, **attrs))
        return f
    return decorator 
Example #11
Source File: decorators.py    From jbox with MIT License 6 votes vote down vote up
def _make_command(f, name, attrs, cls):
    if isinstance(f, Command):
        raise TypeError('Attempted to convert a callback into a '
                        'command twice.')
    try:
        params = f.__click_params__
        params.reverse()
        del f.__click_params__
    except AttributeError:
        params = []
    help = attrs.get('help')
    if help is None:
        help = inspect.getdoc(f)
        if isinstance(help, bytes):
            help = help.decode('utf-8')
    else:
        help = inspect.cleandoc(help)
    attrs['help'] = help
    _check_for_unicode_literals()
    return cls(name=name or f.__name__.lower(),
               callback=f, params=params, **attrs) 
Example #12
Source File: decorators.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def option(*param_decls, **attrs):
    """Attaches an option to the command.  All positional arguments are
    passed as parameter declarations to :class:`Option`; all keyword
    arguments are forwarded unchanged (except ``cls``).
    This is equivalent to creating an :class:`Option` instance manually
    and attaching it to the :attr:`Command.params` list.

    :param cls: the option class to instantiate.  This defaults to
                :class:`Option`.
    """
    def decorator(f):
        if 'help' in attrs:
            attrs['help'] = inspect.cleandoc(attrs['help'])
        OptionClass = attrs.pop('cls', Option)
        _param_memo(f, OptionClass(param_decls, **attrs))
        return f
    return decorator 
Example #13
Source File: decorators.py    From pipenv with MIT License 6 votes vote down vote up
def _make_command(f, name, attrs, cls):
    if isinstance(f, Command):
        raise TypeError("Attempted to convert a callback into a command twice.")
    try:
        params = f.__click_params__
        params.reverse()
        del f.__click_params__
    except AttributeError:
        params = []
    help = attrs.get("help")
    if help is None:
        help = inspect.getdoc(f)
        if isinstance(help, bytes):
            help = help.decode("utf-8")
    else:
        help = inspect.cleandoc(help)
    attrs["help"] = help
    _check_for_unicode_literals()
    return cls(
        name=name or f.__name__.lower().replace("_", "-"),
        callback=f,
        params=params,
        **attrs
    ) 
Example #14
Source File: decorators.py    From pipenv with MIT License 6 votes vote down vote up
def option(*param_decls, **attrs):
    """Attaches an option to the command.  All positional arguments are
    passed as parameter declarations to :class:`Option`; all keyword
    arguments are forwarded unchanged (except ``cls``).
    This is equivalent to creating an :class:`Option` instance manually
    and attaching it to the :attr:`Command.params` list.

    :param cls: the option class to instantiate.  This defaults to
                :class:`Option`.
    """

    def decorator(f):
        # Issue 926, copy attrs, so pre-defined options can re-use the same cls=
        option_attrs = attrs.copy()

        if "help" in option_attrs:
            option_attrs["help"] = inspect.cleandoc(option_attrs["help"])
        OptionClass = option_attrs.pop("cls", Option)
        _param_memo(f, OptionClass(param_decls, **option_attrs))
        return f

    return decorator 
Example #15
Source File: decorators.py    From recruit with Apache License 2.0 6 votes vote down vote up
def option(*param_decls, **attrs):
    """Attaches an option to the command.  All positional arguments are
    passed as parameter declarations to :class:`Option`; all keyword
    arguments are forwarded unchanged (except ``cls``).
    This is equivalent to creating an :class:`Option` instance manually
    and attaching it to the :attr:`Command.params` list.

    :param cls: the option class to instantiate.  This defaults to
                :class:`Option`.
    """
    def decorator(f):
        # Issue 926, copy attrs, so pre-defined options can re-use the same cls=
        option_attrs = attrs.copy()

        if 'help' in option_attrs:
            option_attrs['help'] = inspect.cleandoc(option_attrs['help'])
        OptionClass = option_attrs.pop('cls', Option)
        _param_memo(f, OptionClass(param_decls, **option_attrs))
        return f
    return decorator 
Example #16
Source File: decorators.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _make_command(f, name, attrs, cls):
    if isinstance(f, Command):
        raise TypeError('Attempted to convert a callback into a '
                        'command twice.')
    try:
        params = f.__click_params__
        params.reverse()
        del f.__click_params__
    except AttributeError:
        params = []
    help = attrs.get('help')
    if help is None:
        help = inspect.getdoc(f)
        if isinstance(help, bytes):
            help = help.decode('utf-8')
    else:
        help = inspect.cleandoc(help)
    attrs['help'] = help
    _check_for_unicode_literals()
    return cls(name=name or f.__name__.lower().replace('_', '-'),
               callback=f, params=params, **attrs) 
Example #17
Source File: module.py    From vlcp with Apache License 2.0 6 votes vote down vote up
def registerAPIs(self, apidefs):
        '''
        API definition is in format: `(name, handler, container, discoverinfo)`
        
        if the handler is a generator, container should be specified
        handler should accept two arguments::
        
            def handler(name, params):
                ...
        
        `name` is the method name, `params` is a dictionary contains the parameters.
        
        the handler can either return the result directly, or be a generator (async-api),
        and write the result to container.retvalue on exit.
        e.g::
        
            ('method1', self.method1),    # method1 directly returns the result
            ('method2', self.method2, self) # method2 is an async-api
        
        Use api() to automatically generate API definitions.
        '''
        handlers = [self._createHandler(*apidef) for apidef in apidefs]
        self.handler.registerAllHandlers(handlers)
        self.discoverinfo.update((apidef[0], apidef[3] if len(apidef) > 3 else {'description':cleandoc(apidef[1].__doc__)}) for apidef in apidefs) 
Example #18
Source File: ast.py    From Computable with MIT License 5 votes vote down vote up
def get_docstring(node, clean=True):
    """
    Return the docstring for the given node or None if no docstring can
    be found.  If the node provided does not have docstrings a TypeError
    will be raised.
    """
    if not isinstance(node, (FunctionDef, ClassDef, Module)):
        raise TypeError("%r can't have docstrings" % node.__class__.__name__)
    if node.body and isinstance(node.body[0], Expr) and \
       isinstance(node.body[0].value, Str):
        if clean:
            import inspect
            return inspect.cleandoc(node.body[0].value.s)
        return node.body[0].value.s 
Example #19
Source File: oinspect.py    From Computable with MIT License 5 votes vote down vote up
def getdoc(obj):
    """Stable wrapper around inspect.getdoc.

    This can't crash because of attribute problems.

    It also attempts to call a getdoc() method on the given object.  This
    allows objects which provide their docstrings via non-standard mechanisms
    (like Pyro proxies) to still be inspected by ipython's ? system."""
    # Allow objects to offer customized documentation via a getdoc method:
    try:
        ds = obj.getdoc()
    except Exception:
        pass
    else:
        # if we get extra info, we add it to the normal docstring.
        if isinstance(ds, basestring):
            return inspect.cleandoc(ds)
    
    try:
        docstr = inspect.getdoc(obj)
        encoding = get_encoding(obj)
        return py3compat.cast_unicode(docstr, encoding=encoding)
    except Exception:
        # Harden against an inspect failure, which can occur with
        # SWIG-wrapped extensions.
        raise
        return None 
Example #20
Source File: test_chartbuilder.py    From armada with Apache License 2.0 5 votes vote down vote up
def test_dump(self):
        # Validate base case.
        chart_dir = self.useFixture(fixtures.TempDir())
        self.addCleanup(shutil.rmtree, chart_dir.path)
        self._write_temporary_file_contents(
            chart_dir.path, 'Chart.yaml', self.chart_yaml)
        ch = yaml.safe_load(self.chart_stream)
        ch['data']['source_dir'] = (chart_dir.path, '')

        test_chart = ch
        chartbuilder = ChartBuilder.from_chart_doc(test_chart)
        self.assertRegex(
            repr(chartbuilder.dump()),
            'hello-world-chart.*A sample Helm chart for Kubernetes.*')

        # Validate recursive case (with dependencies).
        dep_chart_dir = self.useFixture(fixtures.TempDir())
        self.addCleanup(shutil.rmtree, dep_chart_dir.path)
        self._write_temporary_file_contents(
            dep_chart_dir.path, 'Chart.yaml', self.dependency_chart_yaml)
        dep_ch = yaml.safe_load(self.dependency_chart_stream)
        dep_ch['data']['source_dir'] = (dep_chart_dir.path, '')

        dependency_chart = dep_ch
        test_chart['data']['dependencies'] = [dependency_chart]
        chartbuilder = ChartBuilder.from_chart_doc(test_chart)

        re = inspect.cleandoc(
            """
            hello-world-chart.*A sample Helm chart for Kubernetes.*
            dependency-chart.*Another sample Helm chart for Kubernetes.*
        """).replace('\n', '').strip()
        self.assertRegex(repr(chartbuilder.dump()), re) 
Example #21
Source File: module.py    From vlcp with Apache License 2.0 5 votes vote down vote up
def create_discover_info(func):
    realf = func
    while hasattr(realf, '__wrapped__'):
        realf = realf.__wrapped__
    argspec = getfullargspec(realf)
    kwargs = argspec.varkw
    arguments = []
    default_value = {}
    if argspec.args:
        args = list(argspec.args)
        if argspec.defaults:
            default_value.update(zip(args[-len(argspec.defaults):], argspec.defaults))
        if hasattr(func, '__self__') and func.__self__:
            # First argument is self, remove an extra argument
            args = args[1:]
        arguments.extend(args)
    if argspec.kwonlyargs:
        arguments.extend(argspec.kwonlyargs)
        if argspec.kwonlydefaults:
            default_value.update(argspec.kwonlydefaults)
    def _create_parameter_definition(name):
        d = {"name": name}
        if name in default_value:
            d['optional'] = True
            d['default'] = default_value[name]
        else:
            d['optional'] = False
        if name in argspec.annotations:
            d['type'] = argspec.annotations[name]
        return d
    info =  {'description': cleandoc(func.__doc__) if func.__doc__ is not None else '',
            'parameters':
                [_create_parameter_definition(n)
                 for n in arguments],
            'extraparameters': bool(kwargs)
            }
    if kwargs and kwargs in argspec.annotations:
        info['extraparameters_type'] = argspec.annotations[kwargs]
    if 'return' in argspec.annotations:
        info['return_type'] = argspec.annotations
    return info 
Example #22
Source File: test_utils.py    From genielibs with Apache License 2.0 5 votes vote down vote up
def test_cli_to_tree_special(self):

        cli = inspect.cleandoc('''
            route-policy SID
              if destination in (192.0.0.4/32) then
                set label-index 100
              else
                pass
              endif
            end-policy
        ''')

        cli_tree = config_cli_to_tree(cli, strip=True)
        self.assertEqual(cli_tree, (
            ('route-policy SID', (
                ('if destination in (192.0.0.4/32) then', (
                    ('set label-index 100', None),
                )),
                ('else', (
                    ('pass', None),
                )),
                ('endif', None),
            )),
            ('end-policy', None),
        ))

        new_cli = cli_tree_to_config(cli_tree)
        self.assertEqual(new_cli, inspect.cleandoc('''
            route-policy SID
             if destination in (192.0.0.4/32) then
              set label-index 100
             else
              pass
             endif
            end-policy
        ''')) 
Example #23
Source File: module.py    From vlcp with Apache License 2.0 5 votes vote down vote up
def registerAPI(self, name, handler, container = None, discoverinfo = None, criteria = None):
        """
        Append new API to this handler
        """
        self.handler.registerHandler(*self._createHandler(name, handler, container, criteria))
        if discoverinfo is None:
            self.discoverinfo[name] = {'description': cleandoc(handler.__doc__)}
        else:
            self.discoverinfo[name] = discoverinfo 
Example #24
Source File: test_inspect.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_cleandoc(self):
        self.assertEqual(inspect.cleandoc('An\n    indented\n    docstring.'),
                         'An\nindented\ndocstring.') 
Example #25
Source File: ast.py    From BinderFilter with MIT License 5 votes vote down vote up
def get_docstring(node, clean=True):
    """
    Return the docstring for the given node or None if no docstring can
    be found.  If the node provided does not have docstrings a TypeError
    will be raised.
    """
    if not isinstance(node, (FunctionDef, ClassDef, Module)):
        raise TypeError("%r can't have docstrings" % node.__class__.__name__)
    if node.body and isinstance(node.body[0], Expr) and \
       isinstance(node.body[0].value, Str):
        if clean:
            import inspect
            return inspect.cleandoc(node.body[0].value.s)
        return node.body[0].value.s 
Example #26
Source File: __init__.py    From mlconjug with MIT License 5 votes vote down vote up
def _getdoc(object):
    """
    Translates the docstrings of the objects defined in the packeage in the supported languages.

    :param object:
    :return: string.
        The translated version of the object's docstring.
    """
    try:
        doc = object.__doc__
    except AttributeError:
        return None
    if not isinstance(doc, str):
        return None
    return inspect.cleandoc(_(doc)) 
Example #27
Source File: corona.py    From Jarvis with MIT License 5 votes vote down vote up
def __call__(self, jarvis, s):
        if 'help' in s:
            jarvis.say(cleandoc(self.__doc__), Fore.GREEN)
        else:
            corona_info = self.get_corona_info(s)
            if corona_info == "URLError":
                jarvis.say(f"Result was not available at the moment. Try again!!", Fore.RED)
            elif corona_info is None:
                jarvis.say(f"Cant find the country \"{s}\"", Fore.RED)
            else:
                location = corona_info["Country"]
                jarvis.say(f"\t+++++++++++++++++++++++++++++++++++++++", Fore.CYAN)
                jarvis.say(f"\tCorona status: \"{location}\"", Fore.CYAN)
                jarvis.say(f"\t+++++++++++++++++++++++++++++++++++++++", Fore.CYAN)

                new_confirmed = corona_info["NewConfirmed"]
                jarvis.say(f"\tNew confirmed cases	: {new_confirmed}", Fore.YELLOW)

                total_confirmed = corona_info["TotalConfirmed"]
                jarvis.say(f"\tTotal confirmed cases	: {total_confirmed}", Fore.YELLOW)

                new_deaths = corona_info["NewDeaths"]
                jarvis.say(f"\tNew deaths		: {new_deaths}", Fore.RED)

                total_deaths = corona_info["TotalDeaths"]
                jarvis.say(f"\tTotal deaths		: {total_deaths}", Fore.RED)

                new_recovered = corona_info["NewRecovered"]
                jarvis.say(f"\tNew recovered		: {new_recovered}", Fore.GREEN)

                total_recovered = corona_info["TotalRecovered"]
                jarvis.say(f"\tTotal recovered		: {total_recovered}", Fore.GREEN) 
Example #28
Source File: stock.py    From Jarvis with MIT License 5 votes vote down vote up
def __call__(self, jarvis, s):
        if not s or 'help' in s:
            jarvis.say(cleandoc(self.__doc__), Fore.GREEN)
        else:
            ps = s.split()
            if ps[0] == 'getid':
                ps.pop(0)
                if ps:
                    name = ' '.join(ps)
                else:
                    name = jarvis.input("Enter the name of the stock: ")
                self.get_stock_id(jarvis, name)
            elif ps[0] == 'profile':
                if(len(ps) != 2):
                    jarvis.say("You forgot to mention the symbol", Fore.RED)
                else:
                    symbol = ps[1]
                    self.get_profile(jarvis, symbol)
            elif ps[0] == 'fstatement':
                if(len(ps) != 2):
                    jarvis.say("You forgot to mention the symbol", Fore.RED)
                else:
                    symbol = ps[1]
                    self.get_financial_stmt(jarvis, symbol)
            elif ps[0] == 'gainers':
                self.get_gainers(jarvis)
            elif ps[0] == 'losers':
                self.get_losers(jarvis)
            # anything else is treated as a stock symbol
            else:
                self.get_stock_data(jarvis, s) 
Example #29
Source File: test_utils.py    From genielibs with Apache License 2.0 5 votes vote down vote up
def test_cli_to_tree_special(self):

        cli = inspect.cleandoc('''
            route-policy SID
              if destination in (192.0.0.4/32) then
                set label-index 100
              else
                pass
              endif
            end-policy
        ''')

        cli_tree = config_cli_to_tree(cli, strip=True)
        self.assertEqual(cli_tree, (
            ('route-policy SID', (
                ('if destination in (192.0.0.4/32) then', (
                    ('set label-index 100', None),
                )),
                ('else', (
                    ('pass', None),
                )),
                ('endif', None),
            )),
            ('end-policy', None),
        ))

        new_cli = cli_tree_to_config(cli_tree)
        self.assertEqual(new_cli, inspect.cleandoc('''
            route-policy SID
             if destination in (192.0.0.4/32) then
              set label-index 100
             else
              pass
             endif
            end-policy
        ''')) 
Example #30
Source File: _toVerilog.py    From myhdl with GNU Lesser General Public License v2.1 5 votes vote down vote up
def _makeDoc(doc, indent=''):
    if doc is None:
        return ''
    doc = inspect.cleandoc(doc)
    pre = '\n' + indent + '// '
    doc = '// ' + doc
    doc = doc.replace('\n', pre)
    return doc