Skip to content

Commit

Permalink
Pass pyright 'basic'
Browse files Browse the repository at this point in the history
  • Loading branch information
mar10 committed Oct 28, 2024
1 parent 3cfe000 commit de2dbcc
Show file tree
Hide file tree
Showing 13 changed files with 58 additions and 35 deletions.
24 changes: 16 additions & 8 deletions nutree/rdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
Functions and declarations to implement `rdflib <https://github.com/RDFLib/rdflib>`_.
"""

# pyright: reportOptionalCall=false
# pyright: reportInvalidTypeForm=false
# pyright: reportGeneralTypeIssues=false
# pyright: reportOptionalMemberAccess=false
# pyright: reportArgumentType=false

from __future__ import annotations

from typing import TYPE_CHECKING, Callable, Union
Expand All @@ -21,15 +27,17 @@
import rdflib
from rdflib import Graph, IdentifiedNode, Literal, URIRef
from rdflib.namespace import RDF, XSD, DefinedNamespace, Namespace
except ImportError: # pragma: no cover

except ImportError:
rdflib = None
Graph = IdentifiedNode = Literal = URIRef = None
RDF = XSD = DefinedNamespace = Namespace = None
# raise


RDFMapperCallbackType = Callable[[Graph, IdentifiedNode, "Node"], Union[None, bool]]

if Namespace:

if rdflib:

class NUTREE_NS(DefinedNamespace):
"""
Expand All @@ -39,16 +47,16 @@ class NUTREE_NS(DefinedNamespace):
_fail = True

# diff_meta:
index: URIRef #
has_child: URIRef #
kind: URIRef #
index: URIRef
has_child: URIRef
kind: URIRef
name: URIRef #
system_root: URIRef #
system_root: URIRef

_NS = Namespace("http://wwwendt.de/namespace/nutree/rdf/0.1/")

else: # rdflib unavailable # pragma: no cover
NUTREE_NS = None
NUTREE_NS = None # type: ignore


def _make_graph() -> Graph:
Expand Down
2 changes: 1 addition & 1 deletion nutree/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def __len__(self):
(also makes empty trees falsy)."""
return self.count

def calc_data_id(self, data) -> DataIdType:
def calc_data_id(self, data: Any) -> DataIdType:
"""Called internally to calculate `data_id` for a `data` object.
This value is used to lookup nodes by data, identify clones, and for
Expand Down
6 changes: 3 additions & 3 deletions nutree/tree_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ class TextRandomizer(Randomizer):
Defaults to 1.0.
"""

def __init__(self, template: Union[str, list], *, probability: float = 1.0) -> None:
def __init__(self, template: str | list[str], *, probability: float = 1.0) -> None:
super().__init__(probability=probability)
if not fab:
raise RuntimeError("Need fabulist installed to generate random text.")
Expand Down Expand Up @@ -275,11 +275,11 @@ class BlindTextRandomizer(Randomizer):
def __init__(
self,
*,
sentence_count: Union[int, tuple] = (2, 6),
sentence_count: int | tuple = (2, 6),
dialect: str = "ipsum",
entropy: int = 2,
keep_first: bool = False,
words_per_sentence: Union[int, tuple] = (3, 15),
words_per_sentence: int | tuple = (3, 15),
probability: float = 1.0,
) -> None:
super().__init__(probability=probability)
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ ignore = [
[tool.pyright]
typeCheckingMode = "basic"
# typeCheckingMode = "off"
reportMissingImports = "none"
# include = ["nutree"]
include = ["nutree", "tests"]
exclude = ["nutree/rdf.py"]
# exclude = ["**/nutree/rdf.py"]

# https://github.com/microsoft/pyright/blob/main/docs/configuration.md#sample-pyprojecttoml-file
reportUnnecessaryTypeIgnoreComment = true
Expand Down
15 changes: 8 additions & 7 deletions tests/fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import tempfile
import time
import timeit
import uuid
from random import randint
from textwrap import dedent, indent
from typing import IO, List
Expand All @@ -26,10 +27,10 @@ def is_running_on_ci() -> bool:


class Person:
def __init__(self, name, *, age, guid=None) -> None:
self.name = name
self.age = age
self.guid = guid
def __init__(self, name: str, *, age: int, guid: str | None = None) -> None:
self.name: str = name
self.age: int = age
self.guid: str = uuid.uuid4().hex if guid is None else guid

def __repr__(self) -> str:
return f"Person<{self.name}, {self.age}>"
Expand All @@ -44,9 +45,9 @@ def __repr__(self) -> str:


class Department:
def __init__(self, name, *, guid=None) -> None:
self.name = name
self.guid = guid
def __init__(self, name: str, *, guid: str | None = None) -> None:
self.name: str = name
self.guid: str = uuid.uuid4().hex if guid is None else guid

def __repr__(self) -> str:
return f"Department<{self.name}>"
Expand Down
2 changes: 1 addition & 1 deletion tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1497,7 +1497,7 @@ def pred(node):
tree_2 = tree.filtered(predicate=None) # type: ignore

with pytest.raises(ValueError, match="Predicate is required"):
tree_2 = tree.system_root.filtered(predicate=None) # type: ignore
tree_2 = tree.system_root.filtered(predicate=None)

tree_2 = tree.copy()

Expand Down
9 changes: 5 additions & 4 deletions tests/test_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php
""" """
# ruff: noqa: T201, T203 `print` found
# pyright: reportOptionalMemberAccess=false

import pytest
from nutree import Tree
Expand Down Expand Up @@ -106,14 +107,14 @@ def test_forward_attrs_true(self):
# Note caveat: `node.name` is not forwardeded, but a native property:
assert let_it_be_node.name == "Item<'Let It Be', 12.34$>"
with pytest.raises(AttributeError):
let_it_be_node.name = "foo" # type: ignore
let_it_be_node.name = "foo"

# `node.price` is alliased to `node.data.price`
assert let_it_be_node.price == 12.34

# forward-attributes are readonly
with pytest.raises(AttributeError):
let_it_be_node.price = 9.99 # type: ignore
let_it_be_node.price = 9.99


class TestDictWrapper:
Expand Down Expand Up @@ -182,7 +183,7 @@ def test_dict(self):

with pytest.raises(TypeError, match="'Node' object is not subscriptable"):
# should NOT support item access via indexing
_ = node["a"] # type: ignore
_ = node["a"]

with pytest.raises(AttributeError):
# should not support attribute access via data
Expand Down Expand Up @@ -250,7 +251,7 @@ class FrozenItem:

# Frozen dataclasses are immutable
with pytest.raises(FrozenInstanceError):
item.count += 1
item.count += 1 # type: ignore

# We can also add by passing the data_id as keyword argument:
_ = tree.add(item, data_id="123-456")
Expand Down
1 change: 1 addition & 0 deletions tests/test_rdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php
""" """
# ruff: noqa: T201, T203 `print` found
# pyright: reportAttributeAccessIssue=false

from nutree.typed_tree import TypedTree

Expand Down
20 changes: 12 additions & 8 deletions tests/test_serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
# Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php
""" """
# ruff: noqa: T201, T203 `print` found
# pyright: reportOptionalMemberAccess=false

from __future__ import annotations

import json
import pprint
Expand Down Expand Up @@ -130,7 +133,7 @@ def _test_serialize_objects(self, *, mode: str):
╰── Node<'Person<Dave, 54>', data_id={456-456}>
"""

def _calc_id(tree, data):
def _calc_id(tree: Tree, data: Any) -> str | int:
# print("calc_id", data)
if isinstance(data, (fixture.Person, fixture.Department)):
return data.guid
Expand Down Expand Up @@ -484,12 +487,12 @@ class MyTree(TypedTree):
}
DEFAULT_VALUE_MAP = {"type": ["person", "dept"]}

def calc_data_id(tree, data):
def calc_data_id(self, data):
if hasattr(data, "guid"):
return data.guid
return hash(data)

def serialize_mapper(self, node: Node, data: dict):
def serialize_mapper(self, node: Node, data: dict) -> dict | None:
if isinstance(node.data, fixture.Department):
data["type"] = "dept"
data["name"] = node.data.name
Expand All @@ -500,17 +503,18 @@ def serialize_mapper(self, node: Node, data: dict):
return data

@staticmethod
def deserialize_mapper(parent: Node, data: dict):
def deserialize_mapper(parent: Node, data: dict) -> str | object | None:
node_type = data["type"]
print("deserialize_mapper", data)
res = data
if node_type == "person":
data = fixture.Person(
res = fixture.Person(
name=data["name"], age=data["age"], guid=data["data_id"]
)
elif node_type == "dept":
data = fixture.Department(name=data["name"], guid=data["data_id"])
print(f"deserialize_mapper -> {data}")
return data
res = fixture.Department(name=data["name"], guid=data["data_id"])
print(f"deserialize_mapper -> {res}")
return res

# Use a TypedTree
tree = MyTree(name="MyTree")
Expand Down
6 changes: 5 additions & 1 deletion tests/test_tree_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,11 @@ def test_fabulist(self):
"__root__": {
"function": {
":count": 3,
"title": TextRandomizer(("{idx}: Provide $(Noun:plural)",)),
"title": TextRandomizer(
[
"{idx}: Provide $(Noun:plural)",
]
),
"details": BlindTextRandomizer(dialect="ipsum"),
"expanded": True,
},
Expand Down
1 change: 1 addition & 0 deletions tests/test_typed_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php
""" """
# ruff: noqa: T201, T203 `print` found
# pyright: reportOptionalMemberAccess=false

import re

Expand Down
2 changes: 2 additions & 0 deletions tests/tutorial_script.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php
""" """
# ruff: noqa: T201, T203 `print` found
# pyright: reportAttributeAccessIssue=false
# pyright: reportOptionalMemberAccess=false

import json

Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ deps =
changedir = {toxinidir}
commands =
pyright nutree tests
ignore_outcome = true
; ignore_outcome = true

[testenv:docs]
description = Build Sphinx documentation (output directory: docs/sphinx-build)
Expand Down

0 comments on commit de2dbcc

Please sign in to comment.