Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove python 3.8 compatibility cruft #749

Merged
merged 2 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions pdoc/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import sys
import warnings

from pdoc._compat import BooleanOptionalAction
import pdoc.doc
import pdoc.extract
import pdoc.render
Expand Down Expand Up @@ -57,7 +56,7 @@
)
renderopts.add_argument(
"--include-undocumented",
action=BooleanOptionalAction,
action=argparse.BooleanOptionalAction,
default=True,
help="Show classes/functions/variables that do not have a docstring.",
)
Expand Down Expand Up @@ -98,25 +97,25 @@
)
renderopts.add_argument(
"--math",
action=BooleanOptionalAction,
action=argparse.BooleanOptionalAction,
default=False,
help="Include MathJax from a CDN to enable math formula rendering.",
)
renderopts.add_argument(
"--mermaid",
action=BooleanOptionalAction,
action=argparse.BooleanOptionalAction,
default=False,
help="Include Mermaid.js from a CDN to enable Mermaid diagram rendering.",
)
renderopts.add_argument(
"--search",
action=BooleanOptionalAction,
action=argparse.BooleanOptionalAction,
default=True,
help="Enable search functionality if multiple modules are documented.",
)
renderopts.add_argument(
"--show-source",
action=BooleanOptionalAction,
action=argparse.BooleanOptionalAction,
default=True,
help='Display "View Source" buttons.',
)
Expand Down
88 changes: 0 additions & 88 deletions pdoc/_compat.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,6 @@
# fmt: off
import sys

if sys.version_info >= (3, 9):
from functools import cache
else: # pragma: no cover
from functools import lru_cache

cache = lru_cache(maxsize=None)

if sys.version_info >= (3, 9):
from ast import unparse as ast_unparse
else: # pragma: no cover
from astunparse import unparse as _unparse

def ast_unparse(t): # type: ignore
return _unparse(t).strip("\t\n \"'")

if sys.version_info >= (3, 12):
from ast import TypeAlias as ast_TypeAlias
else: # pragma: no cover
Expand All @@ -34,33 +19,12 @@ class TypeAliasType:
class TypeAlias:
pass

if sys.version_info >= (3, 9):
from types import GenericAlias
else: # pragma: no cover
from typing import _GenericAlias as GenericAlias

if sys.version_info >= (3, 10):
from types import UnionType # type: ignore
else: # pragma: no cover
class UnionType:
pass

if sys.version_info >= (3, 9):
removesuffix = str.removesuffix
else: # pragma: no cover
def removesuffix(x: str, suffix: str):
if x.endswith(suffix):
x = x[: -len(suffix)]
return x

if sys.version_info >= (3, 9):
removeprefix = str.removeprefix
else: # pragma: no cover
def removeprefix(x: str, prefix: str):
if x.startswith(prefix):
x = x[len(prefix):]
return x


if (3, 9) <= sys.version_info < (3, 9, 8) or (3, 10) <= sys.version_info < (3, 10, 1): # pragma: no cover
import inspect
Expand All @@ -76,53 +40,6 @@ def formatannotation(annotation) -> str:
else:
from inspect import formatannotation

if sys.version_info >= (3, 9):
from argparse import BooleanOptionalAction
else: # pragma: no cover
# https://github.com/python/cpython/pull/27672
from argparse import Action

class BooleanOptionalAction(Action): # pragma: no cover
def __init__(self,
option_strings,
dest,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None):

_option_strings = []
for option_string in option_strings:
_option_strings.append(option_string)

if option_string.startswith('--'):
option_string = '--no-' + option_string[2:]
_option_strings.append(option_string)

if help is not None and default is not None:
help += " (default: %(default)s)"

super().__init__(
option_strings=_option_strings,
dest=dest,
nargs=0,
default=default,
type=type,
choices=choices,
required=required,
help=help,
metavar=metavar)

def __call__(self, parser, namespace, values, option_string=None):
if option_string in self.option_strings:
setattr(namespace, self.dest, not option_string.startswith('--no-'))

def format_usage(self):
return ' | '.join(self.option_strings)


if sys.version_info >= (3, 10):
from typing import is_typeddict
else: # pragma: no cover
Expand All @@ -134,15 +51,10 @@ def is_typeddict(tp):


__all__ = [
"cache",
"ast_unparse",
"ast_TypeAlias",
"TypeAliasType",
"TypeAlias",
"GenericAlias",
"UnionType",
"removesuffix",
"formatannotation",
"BooleanOptionalAction",
"is_typeddict",
]
2 changes: 1 addition & 1 deletion pdoc/doc.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from collections.abc import Callable
import dataclasses
import enum
from functools import cache
from functools import cached_property
from functools import singledispatchmethod
from functools import wraps
Expand All @@ -48,7 +49,6 @@
from pdoc import extract
from pdoc._compat import TypeAlias
from pdoc._compat import TypeAliasType
from pdoc._compat import cache
from pdoc._compat import formatannotation
from pdoc._compat import is_typeddict
from pdoc.doc_types import GenericAlias
Expand Down
5 changes: 2 additions & 3 deletions pdoc/doc_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from collections.abc import Iterable
from collections.abc import Iterator
from dataclasses import dataclass
from functools import cache
import inspect
from itertools import tee
from itertools import zip_longest
Expand All @@ -23,8 +24,6 @@
import pdoc

from ._compat import ast_TypeAlias
from ._compat import ast_unparse
from ._compat import cache

if TYPE_CHECKING:
import pdoc.doc_types
Expand Down Expand Up @@ -81,7 +80,7 @@ def parse(obj):
@cache
def unparse(tree: ast.AST):
"""`ast.unparse`, but cached."""
return ast_unparse(tree)
return ast.unparse(tree)


@dataclass
Expand Down
3 changes: 1 addition & 2 deletions pdoc/doc_pyi.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from __future__ import annotations

from functools import cache
import importlib.util
from pathlib import Path
import sys
Expand All @@ -17,8 +18,6 @@

from pdoc import doc

from ._compat import cache

overload_docstr = typing.overload(lambda: None).__doc__


Expand Down
2 changes: 1 addition & 1 deletion pdoc/doc_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import sys
import types
from types import BuiltinFunctionType
from types import GenericAlias
from types import ModuleType
import typing
from typing import TYPE_CHECKING
Expand All @@ -24,7 +25,6 @@
import warnings

from . import extract
from ._compat import GenericAlias
from ._compat import UnionType
from .doc_ast import type_checking_sections

Expand Down
3 changes: 1 addition & 2 deletions pdoc/docstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from __future__ import annotations

import base64
from functools import cache
import inspect
import mimetypes
import os
Expand All @@ -23,8 +24,6 @@
from textwrap import indent
import warnings

from ._compat import cache


@cache
def convert(docstring: str, docformat: str, source_file: Path | None) -> str:
Expand Down
7 changes: 3 additions & 4 deletions pdoc/render_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from collections.abc import Iterable
from collections.abc import Mapping
from contextlib import contextmanager
from functools import cache
import html
import inspect
import os
Expand All @@ -28,8 +29,6 @@
import pdoc.markdown2

from . import docstrings
from ._compat import cache
from ._compat import removesuffix

lexer = pygments.lexers.PythonLexer()
"""
Expand Down Expand Up @@ -328,7 +327,7 @@ def linkify_repl(m: re.Match):
plain_text = text.replace(
'</span><span class="o">.</span><span class="n">', "."
)
identifier = removesuffix(plain_text, "()")
identifier = plain_text.removesuffix("()")
mod: pdoc.doc.Module = context["module"]

# Check if this is a relative reference. These cannot be local and need to be resolved.
Expand Down Expand Up @@ -462,7 +461,7 @@ def link(context: Context, spec: tuple[str, str], text: str | None = None) -> st
if mod.modulename == modulename:
fullname = qualname
else:
fullname = removesuffix(f"{modulename}.{qualname}", ".")
fullname = f"{modulename}.{qualname}".removesuffix(".")

if qualname:
qualname = f"#{qualname}"
Expand Down
7 changes: 3 additions & 4 deletions pdoc/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from collections.abc import Iterable
from collections.abc import Iterator
from functools import cache
import http.server
import traceback
from typing import Mapping
Expand All @@ -19,8 +20,6 @@
from pdoc import doc
from pdoc import extract
from pdoc import render
from pdoc._compat import cache
from pdoc._compat import removesuffix


class DocHandler(http.server.BaseHTTPRequestHandler):
Expand Down Expand Up @@ -52,15 +51,15 @@ def handle_request(self) -> str:
self.send_header("content-type", "application/javascript")
self.end_headers()
return self.server.render_search_index()
elif "." in removesuffix(path, ".html"):
elif "." in path.removesuffix(".html"):
# See https://github.com/mitmproxy/pdoc/issues/615: All module separators should be normalized to "/".
# We could redirect here, but that would create the impression of a working link, which will fall apart
# when pdoc prerenders to static HTML. So we rather fail early.
self.send_response(404)
self.end_headers()
return "Not Found: Please normalize all module separators to '/'."
else:
module_name = removesuffix(path.lstrip("/"), ".html").replace("/", ".")
module_name = path.lstrip("/").removesuffix(".html").replace("/", ".")
if module_name not in self.server.all_modules:
self.send_response(404)
self.send_header("content-type", "text/html")
Expand Down
Loading