Skip to content

Commit 0073fae

Browse files
committed
REF: More f-strings
1 parent 1961159 commit 0073fae

File tree

3 files changed

+34
-34
lines changed

3 files changed

+34
-34
lines changed

pdoc/__init__.py

+17-17
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,7 @@ def _is_whitelisted(name: str, doc_obj: Union['Module', 'Class']):
375375
Returns `True` if `name` (relative or absolute refname) is
376376
contained in some module's __pdoc__ with a truish value.
377377
"""
378-
refname = doc_obj.refname + '.' + name
378+
refname = f'{doc_obj.refname}.{name}'
379379
module: Optional[Module] = doc_obj.module
380380
while module:
381381
qualname = refname[len(module.refname) + 1:]
@@ -391,7 +391,7 @@ def _is_blacklisted(name: str, doc_obj: Union['Module', 'Class']):
391391
Returns `True` if `name` (relative or absolute refname) is
392392
contained in some module's __pdoc__ with value False.
393393
"""
394-
refname = doc_obj.refname + '.' + name
394+
refname = f'{doc_obj.refname}.{name}'
395395
module: Optional[Module] = doc_obj.module
396396
while module:
397397
qualname = refname[len(module.refname) + 1:]
@@ -587,7 +587,7 @@ def url(self, relative_to: 'Module' = None, *, link_prefix: str = '',
587587
return link_prefix + self._url()
588588

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

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

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

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

915915
def find_ident(self, name: str) -> Doc:
916916
"""
@@ -929,7 +929,7 @@ def find_ident(self, name: str) -> Doc:
929929

930930
return (self.doc.get(_name) or
931931
self._context.get(_name) or
932-
self._context.get(self.name + '.' + _name) or
932+
self._context.get(f'{self.name}.{_name}') or
933933
External(name))
934934

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

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

@@ -1101,7 +1101,7 @@ def _method_type(cls: type, name: str):
11011101

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

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

@@ -1518,16 +1518,16 @@ def __repr__(self):
15181518
annotation = annotation.strip("'")
15191519
if link:
15201520
annotation = re.sub(r'[\w\.]+', _linkify, annotation)
1521-
formatted += ':\N{NBSP}' + annotation
1521+
formatted += f':\N{NBSP}{annotation}'
15221522
if p.default is not EMPTY:
15231523
if p.annotation is not EMPTY:
1524-
formatted += '\N{NBSP}=\N{NBSP}' + repr(p.default)
1524+
formatted += f'\N{NBSP}=\N{NBSP}{repr(p.default)}'
15251525
else:
1526-
formatted += '=' + repr(p.default)
1526+
formatted += f'={repr(p.default)}'
15271527
if p.kind == p.VAR_POSITIONAL:
1528-
formatted = '*' + formatted
1528+
formatted = f'*{formatted}'
15291529
elif p.kind == p.VAR_KEYWORD:
1530-
formatted = '**' + formatted
1530+
formatted = f'**{formatted}'
15311531

15321532
params.append(formatted)
15331533

@@ -1575,7 +1575,7 @@ def _signature_from_string(self):
15751575

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

15801580

15811581
class Variable(Doc):
@@ -1609,12 +1609,12 @@ def __init__(self, name: str, module: Module, docstring, *,
16091609
@property
16101610
def qualname(self) -> str:
16111611
if self.cls:
1612-
return self.cls.qualname + '.' + self.name
1612+
return f'{self.cls.qualname}.{self.name}'
16131613
return self.name
16141614

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

16191619
def type_annotation(self, *, link=None) -> str:
16201620
"""Formatted variable type annotation or empty string if none."""

pdoc/cli.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
mode_aa = parser.add_mutually_exclusive_group().add_argument
2828

2929
aa(
30-
'--version', action='version', version='%(prog)s ' + pdoc.__version__)
30+
'--version', action='version', version=f'%(prog)s {pdoc.__version__}')
3131
aa(
3232
"modules",
3333
type=str,
@@ -366,7 +366,7 @@ def _print_pdf(modules, **kwargs):
366366
def _warn_deprecated(option, alternative='', use_config_mako=False):
367367
msg = f'Program option `{option}` is deprecated.'
368368
if alternative:
369-
msg += ' Use `' + alternative + '`'
369+
msg += f' Use `{alternative}`'
370370
if use_config_mako:
371371
msg += ' or override config.mako template'
372372
msg += '.'

pdoc/html_helpers.py

+15-15
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def _fenced_code_blocks_hidden(text):
9898
def hide(text):
9999
def replace(match):
100100
orig = match.group()
101-
new = '@' + str(hash(orig)) + '@'
101+
new = f'@{hash(orig)}@'
102102
hidden[new] = orig
103103
return new
104104

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

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

237237
@staticmethod
238238
def google(text):
@@ -251,14 +251,14 @@ def googledoc_sections(match):
251251
r'^([\w*]+)(?: \(([\w.,=\[\] -]+)\))?: '
252252
r'((?:.*)(?:\n(?: {2,}.*|$))*)', re.MULTILINE).sub(
253253
lambda m: _ToMarkdown._deflist(*_ToMarkdown._fix_indent(*m.groups())),
254-
inspect.cleandoc('\n' + body)
254+
inspect.cleandoc(f'\n{body}')
255255
)
256256
elif section in ('Returns', 'Yields', 'Raises', 'Warns'):
257257
body = re.compile(
258258
r'^()([\w.,\[\] ]+): '
259259
r'((?:.*)(?:\n(?: {2,}.*|$))*)', re.MULTILINE).sub(
260260
lambda m: _ToMarkdown._deflist(*_ToMarkdown._fix_indent(*m.groups())),
261-
inspect.cleandoc('\n' + body)
261+
inspect.cleandoc(f'\n{body}')
262262
)
263263
# Convert into markdown sections. End underlines with '='
264264
# to avoid matching and re-processing as Numpy sections.
@@ -289,24 +289,24 @@ def _admonition(match, module=None, limit_types=None):
289289
return f'{indent}![{alt_text}]({value})\n'
290290
if type == 'math':
291291
return _ToMarkdown.indent(indent,
292-
'\\[ ' + text.strip() + ' \\]',
292+
f'\\[ {text.strip()} \\]',
293293
clean_first=True)
294294

295295
if type == 'versionchanged':
296-
title = 'Changed in version:&ensp;' + value
296+
title = f'Changed in version:&ensp;{value}'
297297
elif type == 'versionadded':
298-
title = 'Added in version:&ensp;' + value
298+
title = f'Added in version:&ensp;{value}'
299299
elif type == 'deprecated' and value:
300-
title = 'Deprecated since version:&ensp;' + value
300+
title = f'Deprecated since version:&ensp;{value}'
301301
elif type == 'admonition':
302302
title = value
303303
elif type.lower() == 'todo':
304304
title = 'TODO'
305-
text = value + ' ' + text
305+
text = f'{value} {text}'
306306
else:
307307
title = type.capitalize()
308308
if value:
309-
title += ':&ensp;' + value
309+
title += f':&ensp;{value}'
310310

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

366366
@staticmethod
@@ -382,7 +382,7 @@ def raw_urls(text):
382382
)""", re.VERBOSE)
383383

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

388388

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

0 commit comments

Comments
 (0)