Skip to content

Commit

Permalink
REF: More f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
kernc committed Aug 3, 2021
1 parent 1961159 commit 0073fae
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 34 deletions.
34 changes: 17 additions & 17 deletions pdoc/__init__.py
Expand Up @@ -375,7 +375,7 @@ def _is_whitelisted(name: str, doc_obj: Union['Module', 'Class']):
Returns `True` if `name` (relative or absolute refname) is
contained in some module's __pdoc__ with a truish value.
"""
refname = doc_obj.refname + '.' + name
refname = f'{doc_obj.refname}.{name}'
module: Optional[Module] = doc_obj.module
while module:
qualname = refname[len(module.refname) + 1:]
Expand All @@ -391,7 +391,7 @@ def _is_blacklisted(name: str, doc_obj: Union['Module', 'Class']):
Returns `True` if `name` (relative or absolute refname) is
contained in some module's __pdoc__ with value False.
"""
refname = doc_obj.refname + '.' + name
refname = f'{doc_obj.refname}.{name}'
module: Optional[Module] = doc_obj.module
while module:
qualname = refname[len(module.refname) + 1:]
Expand Down Expand Up @@ -587,7 +587,7 @@ def url(self, relative_to: 'Module' = None, *, link_prefix: str = '',
return link_prefix + self._url()

if self.module.name == relative_to.name:
return '#' + self.refname
return f'#{self.refname}'

# Otherwise, compute relative path from current module to link target
url = os.path.relpath(self._url(), relative_to.url()).replace(path.sep, '/')
Expand All @@ -597,7 +597,7 @@ def url(self, relative_to: 'Module' = None, *, link_prefix: str = '',
return url

def _url(self):
return self.module._url() + '#' + self.refname
return f'{self.module._url()}#{self.refname}'

def _inherits_top(self):
"""
Expand Down Expand Up @@ -910,7 +910,7 @@ def find_class(self, cls: type) -> Doc:
# XXX: Is this corrent? Does it always match
# `Class.module.name + Class.qualname`?. Especially now?
# If not, see what was here before.
return self.find_ident((cls.__module__ or _UNKNOWN_MODULE) + '.' + cls.__qualname__)
return self.find_ident(f'{cls.__module__ or _UNKNOWN_MODULE}.{cls.__qualname__}')

def find_ident(self, name: str) -> Doc:
"""
Expand All @@ -929,7 +929,7 @@ def find_ident(self, name: str) -> Doc:

return (self.doc.get(_name) or
self._context.get(_name) or
self._context.get(self.name + '.' + _name) or
self._context.get(f'{self.name}.{_name}') or
External(name))

def _filter_doc_objs(self, type: Type[T], sort=True) -> List[T]:
Expand Down Expand Up @@ -1014,7 +1014,7 @@ def __init__(self, name: str, module: Module, obj, *, docstring: str = None):
init_doc = inspect.getdoc(obj.__init__) or ''
if init_doc == object.__init__.__doc__:
init_doc = ''
docstring = ((inspect.getdoc(obj) or '') + '\n\n' + init_doc).strip()
docstring = f'{inspect.getdoc(obj) or ""}\n\n{init_doc}'.strip()

super().__init__(name, module, obj, docstring=docstring)

Expand Down Expand Up @@ -1101,7 +1101,7 @@ def _method_type(cls: type, name: str):

@property
def refname(self) -> str:
return self.module.name + '.' + self.qualname
return f'{self.module.name}.{self.qualname}'

def mro(self, only_documented=False) -> List['Class']:
"""
Expand Down Expand Up @@ -1464,7 +1464,7 @@ def safe_default_value(p: inspect.Parameter):
if isinstance(value, enum.Enum):
replacement = str(value)
elif inspect.isclass(value):
replacement = (value.__module__ or _UNKNOWN_MODULE) + '.' + value.__qualname__
replacement = f'{value.__module__ or _UNKNOWN_MODULE}.{value.__qualname__}'
elif ' at 0x' in repr(value):
replacement = re.sub(r' at 0x\w+', '', repr(value))

Expand Down Expand Up @@ -1518,16 +1518,16 @@ def __repr__(self):
annotation = annotation.strip("'")
if link:
annotation = re.sub(r'[\w\.]+', _linkify, annotation)
formatted += ':\N{NBSP}' + annotation
formatted += f':\N{NBSP}{annotation}'
if p.default is not EMPTY:
if p.annotation is not EMPTY:
formatted += '\N{NBSP}=\N{NBSP}' + repr(p.default)
formatted += f'\N{NBSP}=\N{NBSP}{repr(p.default)}'
else:
formatted += '=' + repr(p.default)
formatted += f'={repr(p.default)}'
if p.kind == p.VAR_POSITIONAL:
formatted = '*' + formatted
formatted = f'*{formatted}'
elif p.kind == p.VAR_KEYWORD:
formatted = '**' + formatted
formatted = f'**{formatted}'

params.append(formatted)

Expand Down Expand Up @@ -1575,7 +1575,7 @@ def _signature_from_string(self):

@property
def refname(self) -> str:
return (self.cls.refname if self.cls else self.module.refname) + '.' + self.name
return f'{self.cls.refname if self.cls else self.module.refname}.{self.name}'


class Variable(Doc):
Expand Down Expand Up @@ -1609,12 +1609,12 @@ def __init__(self, name: str, module: Module, docstring, *,
@property
def qualname(self) -> str:
if self.cls:
return self.cls.qualname + '.' + self.name
return f'{self.cls.qualname}.{self.name}'
return self.name

@property
def refname(self) -> str:
return (self.cls.refname if self.cls else self.module.refname) + '.' + self.name
return f'{self.cls.refname if self.cls else self.module.refname}.{self.name}'

def type_annotation(self, *, link=None) -> str:
"""Formatted variable type annotation or empty string if none."""
Expand Down
4 changes: 2 additions & 2 deletions pdoc/cli.py
Expand Up @@ -27,7 +27,7 @@
mode_aa = parser.add_mutually_exclusive_group().add_argument

aa(
'--version', action='version', version='%(prog)s ' + pdoc.__version__)
'--version', action='version', version=f'%(prog)s {pdoc.__version__}')
aa(
"modules",
type=str,
Expand Down Expand Up @@ -366,7 +366,7 @@ def _print_pdf(modules, **kwargs):
def _warn_deprecated(option, alternative='', use_config_mako=False):
msg = f'Program option `{option}` is deprecated.'
if alternative:
msg += ' Use `' + alternative + '`'
msg += f' Use `{alternative}`'
if use_config_mako:
msg += ' or override config.mako template'
msg += '.'
Expand Down
30 changes: 15 additions & 15 deletions pdoc/html_helpers.py
Expand Up @@ -98,7 +98,7 @@ def _fenced_code_blocks_hidden(text):
def hide(text):
def replace(match):
orig = match.group()
new = '@' + str(hash(orig)) + '@'
new = f'@{hash(orig)}@'
hidden[new] = orig
return new

Expand Down Expand Up @@ -205,7 +205,7 @@ def _numpy_sections(match):
r'(?: ?: (?P<type>.*))?(?<!\.)$'
r'(?P<desc>(?:\n(?: {4}.*|$))*)',
_ToMarkdown._numpy_params, body, flags=re.MULTILINE)
return section + '\n-----\n' + body
return f'{section}\n-----\n{body}'

@staticmethod
def numpy(text):
Expand All @@ -232,7 +232,7 @@ def _fix_indent(name, type, desc):
def indent(indent, text, *, clean_first=False):
if clean_first:
text = inspect.cleandoc(text)
return re.sub(r'\n', '\n' + indent, indent + text.rstrip())
return re.sub(r'\n', f'\n{indent}', indent + text.rstrip())

@staticmethod
def google(text):
Expand All @@ -251,14 +251,14 @@ def googledoc_sections(match):
r'^([\w*]+)(?: \(([\w.,=\[\] -]+)\))?: '
r'((?:.*)(?:\n(?: {2,}.*|$))*)', re.MULTILINE).sub(
lambda m: _ToMarkdown._deflist(*_ToMarkdown._fix_indent(*m.groups())),
inspect.cleandoc('\n' + body)
inspect.cleandoc(f'\n{body}')
)
elif section in ('Returns', 'Yields', 'Raises', 'Warns'):
body = re.compile(
r'^()([\w.,\[\] ]+): '
r'((?:.*)(?:\n(?: {2,}.*|$))*)', re.MULTILINE).sub(
lambda m: _ToMarkdown._deflist(*_ToMarkdown._fix_indent(*m.groups())),
inspect.cleandoc('\n' + body)
inspect.cleandoc(f'\n{body}')
)
# Convert into markdown sections. End underlines with '='
# to avoid matching and re-processing as Numpy sections.
Expand Down Expand Up @@ -289,24 +289,24 @@ def _admonition(match, module=None, limit_types=None):
return f'{indent}![{alt_text}]({value})\n'
if type == 'math':
return _ToMarkdown.indent(indent,
'\\[ ' + text.strip() + ' \\]',
f'\\[ {text.strip()} \\]',
clean_first=True)

if type == 'versionchanged':
title = 'Changed in version:&ensp;' + value
title = f'Changed in version:&ensp;{value}'
elif type == 'versionadded':
title = 'Added in version:&ensp;' + value
title = f'Added in version:&ensp;{value}'
elif type == 'deprecated' and value:
title = 'Deprecated since version:&ensp;' + value
title = f'Deprecated since version:&ensp;{value}'
elif type == 'admonition':
title = value
elif type.lower() == 'todo':
title = 'TODO'
text = value + ' ' + text
text = f'{value} {text}'
else:
title = type.capitalize()
if value:
title += ':&ensp;' + value
title += f':&ensp;{value}'

text = _ToMarkdown.indent(indent + ' ', text, clean_first=True)
return f'{indent}!!! {type} "{title}"\n{text}\n'
Expand Down Expand Up @@ -360,7 +360,7 @@ def doctests(text):
doctest blocks so they render as Python code.
"""
text = _ToMarkdown.DOCTESTS_RE.sub(
lambda match: '```python-repl\n' + match.group() + '\n```\n', text)
lambda match: f'```python-repl\n{match.group()}\n```\n', text)
return text

@staticmethod
Expand All @@ -382,7 +382,7 @@ def raw_urls(text):
)""", re.VERBOSE)

text = pattern.sub(
lambda m: ('<' + m.group('url') + '>') if m.group('url') else m.group(), text)
lambda m: (f'<{m.group("url")}>') if m.group('url') else m.group(), text)
return text


Expand All @@ -395,7 +395,7 @@ def handleMatch(self, m, data):
for value, is_block in zip(m.groups(), (False, True, True)):
if value:
break
script = etree.Element('script', type='math/tex' + ('; mode=display' if is_block else ''))
script = etree.Element('script', type=f"math/tex{'; mode=display' if is_block else ''}")
preview = etree.Element('span', {'class': 'MathJax_Preview'})
preview.text = script.text = AtomicString(value)
wrapper = etree.Element('span')
Expand Down Expand Up @@ -542,7 +542,7 @@ def extract_toc(text: str):
with _fenced_code_blocks_hidden(text) as result:
result[0] = _ToMarkdown.DOCTESTS_RE.sub('', result[0])
text = result[0]
toc, _ = _md.reset().convert('[TOC]\n\n@CUT@\n\n' + text).split('@CUT@', 1)
toc, _ = _md.reset().convert(f'[TOC]\n\n@CUT@\n\n{text}').split('@CUT@', 1)
if toc.endswith('<p>'): # CUT was put into its own paragraph
toc = toc[:-3].rstrip()
return toc
Expand Down

0 comments on commit 0073fae

Please sign in to comment.