Skip to content

Commit

Permalink
refactor: Improve typing
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed Nov 21, 2021
1 parent f868056 commit e08bcfa
Show file tree
Hide file tree
Showing 16 changed files with 244 additions and 180 deletions.
1 change: 1 addition & 0 deletions config/mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
ignore_missing_imports = true
exclude = tests/fixtures/
warn_unused_ignores = true
show_error_codes = true
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ typing = [
"mypy~=0.910",
"types-markdown~=3.3",
"types-toml~=0.10",
"types-aiofiles~=0.7",
]
security = ["safety~=1.10"]

Expand Down
2 changes: 1 addition & 1 deletion src/griffe/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def main(args: list[str] | None = None) -> int: # noqa: WPS231
An exit code.
"""
parser = get_parser()
opts: argparse.Namespace = parser.parse_args(args) # type: ignore
opts: argparse.Namespace = parser.parse_args(args)

logging.basicConfig(format="%(levelname)-10s %(message)s", level=logging.WARNING) # noqa: WPS323

Expand Down
40 changes: 20 additions & 20 deletions src/griffe/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from functools import cached_property
from pathlib import Path
from textwrap import dedent
from typing import Any, Callable
from typing import Any, Callable, cast

from griffe.collections import LinesCollection, ModulesCollection
from griffe.docstrings.dataclasses import DocstringSection
Expand Down Expand Up @@ -88,7 +88,7 @@ def __init__(
*,
lineno: int | None,
endlineno: int | None,
parent: Module | Class | Function | Attribute | None = None,
parent: Object | None = None,
parser: Parser | None = None,
parser_options: dict[str, Any] | None = None,
) -> None:
Expand All @@ -105,7 +105,7 @@ def __init__(
self.value: str = inspect.cleandoc(value)
self.lineno: int | None = lineno
self.endlineno: int | None = endlineno
self.parent: Module | Class | Function | Attribute | None = parent
self.parent: Object | None = parent
self.parser: Parser | None = parser
self.parser_options: dict[str, Any] = parser_options or {}

Expand Down Expand Up @@ -326,7 +326,7 @@ def __init__(

# attach the docstring to this object
if docstring:
docstring.parent = self # type: ignore
docstring.parent = self

def __repr__(self) -> str:
return f"<{self.__class__.__name__}({self.name!r}, {self.lineno!r}, {self.endlineno!r})>"
Expand Down Expand Up @@ -407,7 +407,7 @@ def modules(self) -> dict[str, Module]:
Returns:
A dictionary of modules.
"""
return {name: member for name, member in self.members.items() if member.kind is Kind.MODULE} # type: ignore
return {name: member for name, member in self.members.items() if member.kind is Kind.MODULE} # type: ignore[misc]

@property
def classes(self) -> dict[str, Class]:
Expand All @@ -416,7 +416,7 @@ def classes(self) -> dict[str, Class]:
Returns:
A dictionary of classes.
"""
return {name: member for name, member in self.members.items() if member.kind is Kind.CLASS} # type: ignore
return {name: member for name, member in self.members.items() if member.kind is Kind.CLASS} # type: ignore[misc]

@property
def functions(self) -> dict[str, Function]:
Expand All @@ -425,7 +425,7 @@ def functions(self) -> dict[str, Function]:
Returns:
A dictionary of functions.
"""
return {name: member for name, member in self.members.items() if member.kind is Kind.FUNCTION} # type: ignore
return {name: member for name, member in self.members.items() if member.kind is Kind.FUNCTION} # type: ignore[misc]

@property
def attributes(self) -> dict[str, Attribute]:
Expand All @@ -434,7 +434,7 @@ def attributes(self) -> dict[str, Attribute]:
Returns:
A dictionary of attributes.
"""
return {name: member for name, member in self.members.items() if member.kind is Kind.ATTRIBUTE} # type: ignore
return {name: member for name, member in self.members.items() if member.kind is Kind.ATTRIBUTE} # type: ignore[misc]

@cached_property
def module(self) -> Module:
Expand Down Expand Up @@ -462,7 +462,7 @@ def package(self) -> Module:
"""
module = self.module
while module.parent:
module = module.parent # type: ignore
module = module.parent # type: ignore[assignment] # always a module
return module

@cached_property
Expand All @@ -486,7 +486,7 @@ def relative_filepath(self) -> Path:
Returns:
A file path.
"""
return self.module.filepath.relative_to(self.package.filepath.parent.parent) # type: ignore
return self.module.filepath.relative_to(self.package.filepath.parent.parent)

@cached_property
def path(self) -> str:
Expand Down Expand Up @@ -710,7 +710,7 @@ def path(self) -> str:
Returns:
A dotted path.
"""
return ".".join((self.parent.path, self.name)) # type: ignore # we assume there's always a parent
return ".".join((self.parent.path, self.name)) # type: ignore[union-attr] # we assume there's always a parent

@cached_property
def modules_collection(self) -> ModulesCollection:
Expand All @@ -720,7 +720,7 @@ def modules_collection(self) -> ModulesCollection:
A modules collection.
"""
# no need to forward to the target
return self.parent.modules_collection # type: ignore # we assume there's always a parent
return self.parent.modules_collection # type: ignore[union-attr] # we assume there's always a parent

@property
def target(self) -> Object | Alias:
Expand All @@ -734,7 +734,7 @@ def target(self) -> Object | Alias:
"""
if not self.resolved:
self.resolve_target()
return self._target # type: ignore # cannot return None, exception is raised
return self._target # type: ignore[return-value] # cannot return None, exception is raised

def resolve_target(self) -> None:
"""Resolve the target.
Expand Down Expand Up @@ -822,7 +822,7 @@ def is_init_module(self) -> bool:
Returns:
True or False.
"""
return self.filepath.name == "__init__.py" # type: ignore
return self.filepath.name == "__init__.py"

@cached_property
def is_package(self) -> bool:
Expand Down Expand Up @@ -861,11 +861,11 @@ def is_namespace_subpackage(self) -> bool:
return (
self.parent
and self.filepath.is_dir()
and self.parent.is_namespace_package # type: ignore # modules parents are always modules
or self.parent.is_namespace_subpackage # type: ignore # modules parents are always modules
and cast(Module, self.parent).is_namespace_package
or cast(Module, self.parent).is_namespace_subpackage
)

def as_dict(self, **kwargs: Any) -> dict[str, Any]: # type: ignore
def as_dict(self, **kwargs: Any) -> dict[str, Any]: # type: ignore[override]
"""Return this module's data as a dictionary.
Parameters:
Expand Down Expand Up @@ -903,7 +903,7 @@ def __init__(
self.bases: list[Name | Expression] = bases or []
self.decorators: list[Decorator] = decorators or []

def as_dict(self, **kwargs: Any) -> dict[str, Any]: # type: ignore
def as_dict(self, **kwargs: Any) -> dict[str, Any]: # type: ignore[override]
"""Return this class' data as a dictionary.
Parameters:
Expand Down Expand Up @@ -945,7 +945,7 @@ def __init__(
self.returns: str | Name | Expression | None = returns
self.decorators: list[Decorator] = decorators or []

def as_dict(self, **kwargs: Any) -> dict[str, Any]: # type: ignore
def as_dict(self, **kwargs: Any) -> dict[str, Any]: # type: ignore[override]
"""Return this function's data as a dictionary.
Parameters:
Expand Down Expand Up @@ -985,7 +985,7 @@ def __init__(
self.value: str | None = value
self.annotation: str | Name | Expression | None = annotation

def as_dict(self, **kwargs: Any) -> dict[str, Any]: # type: ignore
def as_dict(self, **kwargs: Any) -> dict[str, Any]: # type: ignore[override]
"""Return this function's data as a dictionary.
Parameters:
Expand Down
20 changes: 10 additions & 10 deletions src/griffe/docstrings/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,22 +168,22 @@ def _read_parameters(docstring: Docstring, offset: int) -> tuple[list[DocstringP
if " " in name_with_type:
name, annotation = name_with_type.split(" ", 1)
annotation = annotation.strip("()")
if annotation.endswith(", optional"): # type: ignore
annotation = annotation[:-10] # type: ignore
if annotation.endswith(", optional"):
annotation = annotation[:-10]
# try to compile the annotation to transform it into an expression
with suppress(SyntaxError, AttributeError):
code = compile(annotation, mode="eval", filename="", flags=PyCF_ONLY_AST, optimize=2)
annotation = get_annotation(code.body, parent=docstring.parent) # type: ignore
annotation = code.body and get_annotation(code.body, parent=docstring.parent) # type: ignore[arg-type]
else:
name = name_with_type
# try to use the annotation from the signature
try:
annotation = docstring.parent.parameters[name].annotation # type: ignore
annotation = docstring.parent.parameters[name].annotation # type: ignore[union-attr]
except (AttributeError, KeyError):
annotation = None

try:
default = docstring.parent.parameters[name].default # type: ignore
default = docstring.parent.parameters[name].default # type: ignore[union-attr]
except (AttributeError, KeyError):
default = None

Expand Down Expand Up @@ -237,11 +237,11 @@ def _read_attributes_section(docstring: Docstring, offset: int) -> tuple[Docstri
# try to compile the annotation to transform it into an expression
with suppress(SyntaxError):
code = compile(annotation, mode="eval", filename="", flags=PyCF_ONLY_AST, optimize=2)
annotation = get_annotation(code.body, parent=docstring.parent) # type: ignore
annotation = code.body and get_annotation(code.body, parent=docstring.parent) # type: ignore[arg-type]
else:
name = name_with_type
try:
annotation = docstring.parent.attributes[name].annotation # type: ignore
annotation = docstring.parent.attributes[name].annotation # type: ignore[union-attr]
except (AttributeError, KeyError):
annotation = None

Expand Down Expand Up @@ -309,7 +309,7 @@ def _read_returns_section(docstring: Docstring, offset: int) -> tuple[DocstringS
description = text
# try to use the annotation from the signature
try: # noqa: WPS505
annotation = docstring.parent.returns # type: ignore
annotation = docstring.parent.returns # type: ignore[union-attr]
except AttributeError:
annotation = None
else:
Expand Down Expand Up @@ -342,7 +342,7 @@ def _read_yields_section(docstring: Docstring, offset: int) -> tuple[DocstringSe
# try to use the annotation from the signature
try: # noqa: WPS505
# TODO: handle Iterator and Generator types
annotation = docstring.parent.returns # type: ignore
annotation = docstring.parent.returns # type: ignore[union-attr]
except AttributeError:
annotation = None
else:
Expand Down Expand Up @@ -375,7 +375,7 @@ def _read_receives_section(docstring: Docstring, offset: int) -> tuple[Docstring
# try to use the annotation from the signature
try: # noqa: WPS505
# TODO: handle Iterator and Generator types
annotation = docstring.parent.returns # type: ignore
annotation = docstring.parent.returns # type: ignore[union-attr]
except AttributeError:
annotation = None
else:
Expand Down
12 changes: 6 additions & 6 deletions src/griffe/docstrings/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from __future__ import annotations

import re
from contextlib import suppress
from textwrap import dedent
from typing import TYPE_CHECKING, Any, Pattern

Expand All @@ -54,6 +55,7 @@
DocstringYield,
)
from griffe.docstrings.utils import warning
from griffe.expressions import Expression, Name

if TYPE_CHECKING:
from griffe.dataclasses import Docstring
Expand Down Expand Up @@ -192,7 +194,7 @@ def _read_block(docstring: Docstring, offset: int) -> tuple[str, int]:

def _read_parameters(docstring: Docstring, offset: int) -> tuple[list[DocstringParameter], int]: # noqa: WPS231
parameters = []
annotation: str | None
annotation: str | Name | Expression | None

items, index = _read_block_items(docstring, offset)

Expand All @@ -219,18 +221,16 @@ def _read_parameters(docstring: Docstring, offset: int) -> tuple[list[DocstringP
if annotation is None:
# try to use the annotation from the signature
for name in names:
try:
annotation = docstring.parent.parameters[name].annotation # type: ignore
with suppress(AttributeError, KeyError):
annotation = docstring.parent.parameters[name].annotation # type: ignore[union-attr]
break
except (AttributeError, KeyError):
pass
else:
_warn(docstring, index, f"No types or annotations for parameters {names}")

if default is None:
for name in names:
try:
default = docstring.parent.parameters[name].default # type: ignore
default = docstring.parent.parameters[name].default # type: ignore[union-attr]
break
except (AttributeError, KeyError):
pass
Expand Down
Loading

0 comments on commit e08bcfa

Please sign in to comment.