我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.cleandoc()。
def installed_plugins(self): """List all plugins installed.""" from os import listdir from fnmatch import fnmatch import compiler import inspect files = listdir('Plugins') try: files.remove('mount.py') files.remove('template.py') except ValueError: pass plugins = {} for element in files: if fnmatch(element, '*.py') and not fnmatch(element, '_*'): plug_doc = compiler.parseFile('Plugins/' + element).doc plug_doc = inspect.cleandoc(plug_doc) plugins[element[:-3]] = plug_doc # Remove .py) return plugins
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)
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
def generate_comment(self): docs = [] for ext in self.bot.extensions: doc = ext.__class__.__doc__ if not doc: continue docs.append(inspect.cleandoc(doc)) help_ = '\n\n'.join(docs) return self.HELP % dict( extensions=','.join(sorted(self.bot.extensions_map.keys())), help=help_, host=socket.getfqdn(), me=self.current.head.repository.SETTINGS.NAME, mentions=', '.join(sorted([ '@' + m for m in self.current.help_mentions ])), software=self.DISTRIBUTION.project_name, version=self.DISTRIBUTION.version, )
def parse_docstring(s): title = [] description = [] strings = inspect.cleandoc(s).split("\n") for i, x in enumerate(strings): if x: title.append(x) else: if title: description = strings[i + 1:] break else: continue return { "title": " ".join(title), "description": " ".join(description) }
def test_orderedDict(): """ Do I keep the order of dicts? """ dct = openapi.UnsortableOrderedDict() dct['a'] = 1 dct['z'] = 2 dct['b'] = 3 dct['y'] = 4 dct['c'] = 5 dct['x'] = 6 assert yaml.dump(dct, default_flow_style=False) == cleandoc(''' a: 1 z: 2 b: 3 y: 4 c: 5 x: 6 ''') + '\n'
def test_openapiDoc(): """ Do I update the function I'm called with? """ def fn(): """ This function has some stuff for sure --- a: b """ fn = tree.openAPIDoc(foo={'c': 'd'})(fn) expected = cleandoc(''' This function has some stuff for sure --- a: b --- foo: c: d ''') + '\n' assert fn.__doc__ == expected
def openAPIDoc(**kwargs): """ Update a function's docstring to include the OpenAPI Yaml generated by running the openAPIGraph object """ s = yaml.dump(kwargs, default_flow_style=False) def deco(routeHandler): # Wrap routeHandler, retaining name and __doc__, then edit __doc__. # The only reason we need to do this is so we can be certain # that __doc__ will be modifiable. partial() objects have # a modifiable __doc__, but native function objects do not. ret = functools.wraps(routeHandler)(routeHandler) if not ret.__doc__: ret.__doc__ = '' ret.__doc__ = cleandoc(ret.__doc__) + '\n---\n' + s return ret return deco
def test_custom_primary_command(create_project, run): """Test creating a command that overwrites the primary command.""" usage = ''' Usage: hello [--name <name>] Options: --name <name> The name to print [default: world]. ''' with create_project(''' def hello(name): """{usage}""" print('Hello, {{name}}!'.format(name=name)) '''.format(usage=usage)): assert run('hello --name everyone') == 'Hello, everyone!\n' assert run('hello') == 'Hello, world!\n' assert inspect.cleandoc(run('hello -h')) == inspect.cleandoc(usage)
def _wrap_section(source, width): # type: (str, int) -> str """Wrap the given section string to the current terminal size. Intelligently wraps the section string to the given width. When wrapping section lines, it auto-adjusts the spacing between terms and definitions. It also adjusts commands the fit the correct length for the arguments. Args: source: The section string to wrap. Returns: The wrapped section string. """ if _get_section('usage', source): return _wrap_usage_section(source, width) if _is_definition_section(source): return _wrap_definition_section(source, width) lines = inspect.cleandoc(source).splitlines() paragraphs = (textwrap.wrap(line, width, replace_whitespace=False) for line in lines) return '\n'.join(line for paragraph in paragraphs for line in paragraph)
def _parse_func_code(lines): from inspect import cleandoc if len(lines) == 1: _ = lines[0].split(':', 1) return [_[0] + ':'], '', _[1] sig, doc = [], [] while lines: l = lines.pop(0) sig.append(l) if l.rstrip().endswith(':'): break l = '\n'.join(lines).strip() for apo in "'''", '"""', "'", '"', '': if l.startswith(apo): break if not apo: # no docstring return sig, '', lines l = l.split(apo, 2) return sig, cleandoc(l[1]), l[2]