Skip to content

Commit

Permalink
[cdd/tests/mocks/exmod.py] Fix imports after find/replace (also fix `…
Browse files Browse the repository at this point in the history
…node.s` usage; so that branch is reachable); [cdd/**/*.py] Increase type annotation coverage
  • Loading branch information
SamuelMarks committed Dec 23, 2023
1 parent 3f413a3 commit 3961437
Show file tree
Hide file tree
Showing 26 changed files with 96 additions and 72 deletions.
2 changes: 1 addition & 1 deletion cdd/argparse_function/utils/emit_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def parse_out_param(expr, require_default=False, emit_default_doc=True):
),
"str",
)
name = get_value(expr.value.args[0])[len("--") :]
name: str = get_value(expr.value.args[0])[len("--") :]
default = next(
(
get_value(key_word.value)
Expand Down
6 changes: 3 additions & 3 deletions cdd/class_/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ def _class_from_memory(
"from_type": "cls",
}
if class_name is None:
class_name = parsed_body.name
class_name: Optional[str] = parsed_body.name
body_ir: IntermediateRepr = class_(
class_def=parsed_body,
class_name=class_name,
Expand Down Expand Up @@ -358,7 +358,7 @@ def _merge_inner_function(
})
:rtype: ```dict```
"""
function_def = next(
function_def: Optional[FunctionDef] = next(
filter(
lambda func: func.name == merge_inner_function,
filter(rpartial(isinstance, FunctionDef), ast.walk(class_def)),
Expand All @@ -367,7 +367,7 @@ def _merge_inner_function(
)

if function_def is not None:
function_type = (
function_type: str = (
"static" if not function_def.args.args else function_def.args.args[0].arg
)
inner_ir: IntermediateRepr = cdd.function.parse.function(
Expand Down
3 changes: 2 additions & 1 deletion cdd/compound/exmod.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from itertools import chain, groupby
from operator import attrgetter, itemgetter
from os import makedirs, path
from typing import Optional

import cdd.class_.parse
import cdd.compound.exmod_utils
Expand Down Expand Up @@ -99,7 +100,7 @@ def exmod(
elif not path.isdir(output_directory):
makedirs(output_directory)

emit_name = (
emit_name: Optional[str] = (
emit_name[0]
if emit_name is not None
and len(emit_name) == 1
Expand Down
3 changes: 2 additions & 1 deletion cdd/compound/exmod_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from operator import attrgetter, eq
from os import environ, extsep, makedirs, path
from sys import stdout
from typing import Optional

import cdd.argparse_function.emit
import cdd.class_
Expand Down Expand Up @@ -236,7 +237,7 @@ def emit_file_on_hierarchy(
if relative_filename_path.startswith(module_name_as_path + path.sep):
relative_filename_path = relative_filename_path[len(new_module_name_as_path) :]
if not name and ir.get("name") is not None:
name = ir.get("name")
name: Optional[str] = ir.get("name")

output_dir_is_module = output_directory.replace(path.sep, ".").endswith(
new_module_name
Expand Down
2 changes: 1 addition & 1 deletion cdd/compound/gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def gen(

module_path, _, symbol_name = input_mapping.rpartition(".")

emit_name = sanitise_emit_name(emit_name)
emit_name: str = sanitise_emit_name(emit_name)
if path.isfile(input_mapping):
input_mapping = file_to_input_mapping(input_mapping, parse_name)
elif path.isdir(input_mapping):
Expand Down
8 changes: 4 additions & 4 deletions cdd/compound/openapi/gen_openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,15 @@ def construct_parameters_and_request_bodies(route, path_dict):
"""
if ":" in route:
path_dict["parameters"] = []
object_name = path_dict.get(
object_name: str = path_dict.get(
"get", path_dict.get("delete", {"summary": "`Object`"})
)["summary"]
fst = object_name.find("`")
object_name = (
fst: int = object_name.find("`")
object_name: str = (
object_name[fst + 1 : object_name.find("`", fst + 1)] or "Object"
)

route = "/".join(
route: str = "/".join(
map(
lambda r: (
lambda pk: (
Expand Down
2 changes: 1 addition & 1 deletion cdd/shared/cst_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ def cst_parse_one_node(statement, state):

if words:
if len(words) > 1:
name = get_construct_name(words)
name: Optional[str] = get_construct_name(words)
if name is not None:
return (
ClassDefinitionStart
Expand Down
12 changes: 6 additions & 6 deletions cdd/shared/docstring_parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ def _set_name_and_type(param, infer_type, word_wrap, none_default_for_kwargs=Fal
)

if name is not None and (name.endswith("kwargs") or name.startswith("**")):
name = name.lstrip("*")
name: str = name.lstrip("*")
if _param.get("typ", "dict") == "dict":
_param["typ"] = "Optional[dict]"
# if (
Expand All @@ -535,7 +535,7 @@ def _set_name_and_type(param, infer_type, word_wrap, none_default_for_kwargs=Fal
# ) and none_default_for_kwargs:
# _param["default"] = NoneStr
elif name is not None and name.startswith("*"):
name = name[1:]
name: str = name[1:]
if _param.get("typ") is None:
_param["typ"] = "tuple"
if "default" not in _param:
Expand Down Expand Up @@ -969,16 +969,16 @@ def _parse_phase_rest(
)[1]
)
else:
fst_space = line.find(" ")
nxt_colon = line.find(":", fst_space)
name = line[fst_space + 1 : nxt_colon]
fst_space: int = line.find(" ")
nxt_colon: int = line.find(":", fst_space)
name: str = line[fst_space + 1 : nxt_colon]

if param[0] is not None and not param[0] == name:
if not param[0][0] == "*":
intermediate_repr["params"][param[0]] = param[1]
param = [None, {}]

val = (lambda s_: s_ if parse_original_whitespace else s_.strip())(
val: str = (lambda s_: s_ if parse_original_whitespace else s_.strip())(
line[nxt_colon + 1 :]
)

Expand Down
2 changes: 1 addition & 1 deletion cdd/shared/parse/utils/parser_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ def get_parser(node, parse_name):
:rtype: ```Callable[[...], dict]````
"""
if parse_name in (None, "infer"):
parse_name = infer(node)
parse_name: str = infer(node)
parse_name = {
"class": "class_",
"sqlalchemy_hybrid": "sqlalchemy",
Expand Down
2 changes: 2 additions & 0 deletions cdd/shared/pure_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ def identity(*args, **kwargs):
PY_GTE_3_8: bool = _python_major_minor >= (3, 8)
PY_GTE_3_9: bool = _python_major_minor >= (3, 9)
PY_GTE_3_10: bool = _python_major_minor >= (3, 10)
PY_GTE_3_11: bool = _python_major_minor >= (3, 11)
PY_GTE_3_12: bool = _python_major_minor >= (3, 12)

ENCODING = "# -*- coding: utf-8 -*-"
Expand Down Expand Up @@ -1278,6 +1279,7 @@ def namespaced_upper_camelcase_to_pascal(s, sep="__"):
"ENCODING",
"INIT_FILENAME",
"PY3_8",
"PY_GTE_3_11",
"PY_GTE_3_12",
"PY_GTE_3_8",
"PY_GTE_3_9",
Expand Down
24 changes: 17 additions & 7 deletions cdd/shared/types.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
"""
Shared types
"""
from _ast import AnnAssign, Assign

from cdd.shared.pure_utils import PY_GTE_3_8, PY_GTE_3_9
from ast import AnnAssign, Assign

from cdd.shared.pure_utils import PY_GTE_3_8, PY_GTE_3_9, PY_GTE_3_11

if PY_GTE_3_8:
if PY_GTE_3_9:
from collections import OrderedDict
else:
from typing import OrderedDict
from typing import Any, List, Optional, Required, TypedDict, Union
from typing import Any, List, Optional, TypedDict, Union

if PY_GTE_3_11:
from typing import Required
else:
from typing_extensions import Required
else:
from typing_extensions import (
Any,
Expand All @@ -33,15 +39,19 @@


ParamVal = TypedDict("ParamVal", {"typ": str, "doc": Optional[str], "default": Any})
Internal = TypedDict(
"Internal",
{
"original_doc_str": Optional[str],
"body": List[Union[AnnAssign, Assign]],
},
)
IntermediateRepr = TypedDict(
"IntermediateRepr",
{
"name": Required[Optional[str]],
"type": Optional[str],
"_internal": {
"original_doc_str": Optional[str],
"body": List[Union[AnnAssign, Assign]],
},
"_internal": Internal,
"doc": Required[Optional[str]],
"params": Required[OrderedDict[str, ParamVal]],
"returns": Required[
Expand Down
3 changes: 2 additions & 1 deletion cdd/sqlalchemy/emit.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from itertools import chain
from operator import add
from os import environ
from typing import Optional

import cdd.compound.openapi.utils.emit_utils
from cdd.docstring.emit import docstring
Expand Down Expand Up @@ -225,7 +226,7 @@ def sqlalchemy(
"""

if class_name is None and intermediate_repr["name"]:
class_name = intermediate_repr["name"]
class_name: Optional[str] = intermediate_repr["name"]
assert class_name is not None, "`class_name` is `None`"

return ClassDef(
Expand Down
6 changes: 3 additions & 3 deletions cdd/tests/mocks/exmod.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
extracts the `__author__` and `__version__`
"""
from ast import Assign, set_value, Str, parse
from ast import Assign, Constant, Str, parse
from operator import attrgetter
from os import path
from os.path import extsep
Expand All @@ -30,9 +30,9 @@ def main():
parsed_init = parse(f.read())
__author__, __version__ = map(
lambda node: node.value if isinstance(node, set_value) else node.s,
lambda node: node.s if isinstance(node, Str) else node.value,
filter(
lambda node: isinstance(node, (set_value, Str)),
lambda node: isinstance(node, (Constant, Str)),
map(
attrgetter("value"),
filter(lambda node: isinstance(node, Assign), parsed_init.body),
Expand Down
4 changes: 2 additions & 2 deletions cdd/tests/test_cli/test_cli_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def test_gen_fails(self) -> None:
def test_existent_file_fails(self) -> None:
"""Tests nonexistent file throws the right error"""
with TemporaryDirectory() as tempdir:
filename = os.path.join(
filename: str = os.path.join(
tempdir,
"delete_this_1{__file___basename}".format(
__file___basename=os.path.basename(__file__)
Expand Down Expand Up @@ -55,7 +55,7 @@ def test_existent_file_fails(self) -> None:
def test_gen(self) -> None:
"""Tests CLI interface gets all the way to the gen call without error"""
with TemporaryDirectory() as tempdir:
output_filename = os.path.join(
output_filename: str = os.path.join(
tempdir, "classes{extsep}py".format(extsep=extsep)
)

Expand Down
12 changes: 6 additions & 6 deletions cdd/tests/test_cli/test_cli_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def test_version(self) -> None:
def test_args_example0(self) -> None:
"""Tests CLI interface sets namespace correctly"""
with TemporaryDirectory() as tempdir:
filename = os.path.join(
filename: str = os.path.join(
os.path.realpath(tempdir),
"delete_this_0{}".format(os.path.basename(__file__)),
)
Expand Down Expand Up @@ -70,15 +70,15 @@ def test_args_example1(self) -> None:
"""Tests CLI interface sets namespace correctly"""

with TemporaryDirectory() as tempdir:
argparse_filename = os.path.join(
argparse_filename: str = os.path.join(
os.path.realpath(tempdir),
"argparse{extsep}py".format(extsep=extsep),
)
class_filename = os.path.join(
class_filename: str = os.path.join(
os.path.realpath(tempdir),
"class_{extsep}py".format(extsep=extsep),
)
method_filename = os.path.join(
method_filename: str = os.path.join(
os.path.realpath(tempdir),
"method{extsep}py".format(extsep=extsep),
)
Expand Down Expand Up @@ -125,7 +125,7 @@ def test_args_example1(self) -> None:
def test_non_existent_file_fails(self) -> None:
"""Tests nonexistent file throws the right error"""
with TemporaryDirectory() as tempdir:
filename = os.path.join(
filename: str = os.path.join(
os.path.realpath(tempdir),
"delete_this_1{}".format(os.path.basename(__file__)),
)
Expand Down Expand Up @@ -159,7 +159,7 @@ def test_missing_argument_fails(self) -> None:
def test_missing_argument_fails_insufficient_args(self) -> None:
"""Tests missing argument throws the right error"""
with TemporaryDirectory() as tempdir:
filename = os.path.join(
filename: str = os.path.join(
os.path.realpath(tempdir),
"delete_this_2{}".format(os.path.basename(__file__)),
)
Expand Down
10 changes: 5 additions & 5 deletions cdd/tests/test_cli/test_cli_sync_properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def test_sync_properties_fails(self) -> None:
def test_non_existent_file_fails(self) -> None:
"""Tests nonexistent file throws the right error"""
with TemporaryDirectory() as tempdir:
filename = os.path.join(
filename: str = os.path.join(
tempdir,
"delete_this_1{}".format(os.path.basename(__file__)),
)
Expand All @@ -50,11 +50,11 @@ def test_non_existent_file_fails(self) -> None:
)

with TemporaryDirectory() as tempdir:
input_filename = os.path.join(
input_filename: str = os.path.join(
tempdir,
"input_filename{extsep}py".format(extsep=extsep),
)
output_filename = os.path.join(
output_filename: str = os.path.join(
tempdir,
"output_filename{extsep}py".format(extsep=extsep),
)
Expand Down Expand Up @@ -82,10 +82,10 @@ def test_non_existent_file_fails(self) -> None:
def test_sync_properties(self) -> None:
"""Tests CLI interface gets all the way to the sync_properties call without error"""
with TemporaryDirectory() as tempdir:
input_filename = os.path.join(
input_filename: str = os.path.join(
tempdir, "class_{extsep}py".format(extsep=extsep)
)
output_filename = os.path.join(
output_filename: str = os.path.join(
tempdir, "method{extsep}py".format(extsep=extsep)
)
open(input_filename, "wt").close()
Expand Down
12 changes: 6 additions & 6 deletions cdd/tests/test_compound/test_exmod.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@
class TestExMod(TestCase):
"""Test class for exmod.py"""

parent_name = ""
parent_dir = ""
child_name = ""
child_dir = ""
grandchild_name = ""
grandchild_dir = ""
parent_name: str = ""
parent_dir: str = ""
child_name: str = ""
child_dir: str = ""
grandchild_name: str = ""
grandchild_dir: str = ""
module_hierarchy = ()

@classmethod
Expand Down
Loading

0 comments on commit 3961437

Please sign in to comment.