Skip to content

Commit

Permalink
fixed linting
Browse files Browse the repository at this point in the history
  • Loading branch information
sneakers-the-rat committed Oct 28, 2024
1 parent 58b5fc7 commit 23b8ea9
Show file tree
Hide file tree
Showing 22 changed files with 78 additions and 78 deletions.
17 changes: 6 additions & 11 deletions linkml_runtime/index/object_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@

import inspect
import logging
from collections.abc import Iterator, Mapping
from typing import Any, Union
from collections.abc import Iterator, MutableMapping
from typing import Any

from linkml_runtime import SchemaView
from linkml_runtime.utils import eval_utils
Expand Down Expand Up @@ -56,9 +56,9 @@ def __init__(self, obj: YAMLRoot, schemaview: SchemaView):
self._root_object = obj
self._schemaview = schemaview
self._class_map = schemaview.class_name_mappings()
self._source_object_cache: Mapping[str, Any] = {}
self._proxy_object_cache: Mapping[str, ProxyObject] = {}
self._child_to_parent: Mapping[str, list[tuple[str, str]]] = {}
self._source_object_cache: MutableMapping[str, Any] = {}
self._proxy_object_cache: MutableMapping[str, ProxyObject] = {}
self._child_to_parent: MutableMapping[str, list[tuple[str, str]]] = {}
self._index(obj)

def _index(self, obj: Any, parent_key=None, parent=None):
Expand All @@ -70,16 +70,11 @@ def _index(self, obj: Any, parent_key=None, parent=None):
return {k: self._index(v, parent_key, parent) for k, v in obj.items()}
cls_name = type(obj).__name__
if cls_name in self._class_map:
cls = self._class_map[cls_name]
pk_val = self._key(obj)
self._source_object_cache[pk_val] = obj
if pk_val not in self._child_to_parent:
self._child_to_parent[pk_val] = []
self._child_to_parent[pk_val].append((parent_key, parent))
# id_slot = self._schemaview.get_identifier_slot(cls.name)
# if id_slot:
# id_val = getattr(obj, id_slot.name)
# self._source_object_cache[(cls.name, id_val)] = obj
for k, v in vars(obj).items():
self._index(v, k, obj)
else:
Expand Down Expand Up @@ -115,7 +110,7 @@ def bless(self, obj: Any) -> "ProxyObject":
else:
return ProxyObject(obj, _db=self)

def _key(self, obj: Any) -> tuple[Union[str, YAMLRoot], str]:
def _key(self, obj: Any) -> tuple[str, str]:
"""
Returns primary key value for this object.
Expand Down
3 changes: 2 additions & 1 deletion linkml_runtime/loaders/rdf_loader.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
from typing import Optional, TextIO, Union

from hbreader import FileInfo
Expand Down Expand Up @@ -85,7 +86,7 @@ def loader(data: Union[str, dict], _: FileInfo) -> Optional[dict]:

# If the input is a graph, convert it to JSON-LD
if isinstance(source, Graph):
source = pyld_jsonld_from_rdflib_graph(source)
source = pyld_jsonld_from_rdflib_graph(source) # noqa: F821 - no idea what this is
jsonld_str = source.serialize(format="json-ld", indent=4)
source = json.loads(jsonld_str)
fmt = "json-ld"
Expand Down
6 changes: 3 additions & 3 deletions linkml_runtime/loaders/rdflib_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ def from_rdf_graph(
:param schemaview: schema to which graph conforms
:param target_class: class which root nodes should instantiate
:param prefix_map: additional prefix mappings for data objects
:param ignore_unmapped_predicates: if True then a predicate that has no mapping to a slot does not raise an error
:param ignore_unmapped_predicates:
if True then a predicate that has no mapping to a slot does not raise an error
:return: all instances of target class type
"""
namespaces = schemaview.namespaces()
Expand Down Expand Up @@ -231,8 +232,7 @@ def _get_id_dict(self, node: VALID_SUBJECT, schemaview: SchemaView, cn: ClassDef
id_slot = schemaview.get_identifier_slot(cn)
if not isinstance(node, BNode):
id_val = self._uri_to_id(node, id_slot, schemaview)
# id_val = schemaview.namespaces().curie_for(node)
if id_val == None:
if id_val is None:
id_val = str(node)
return {id_slot.name: id_val}
else:
Expand Down
2 changes: 1 addition & 1 deletion linkml_runtime/processing/referencevalidator.py
Original file line number Diff line number Diff line change
Expand Up @@ -667,7 +667,7 @@ def ensure_simple_dict(
) -> Any:
simple_dict_value_slot = self._slot_as_simple_dict_value_slot(parent_slot)
if not simple_dict_value_slot:
raise AssertionError(f"Should have simple dict slot valie: {parent_slot.name}")
raise AssertionError(f"Should have simple dict slot value: {parent_slot.name}")
normalized_object = input_object
if isinstance(input_object, list):
normalized_object = {v[pk_slot_name]: v for v in input_object}
Expand Down
6 changes: 4 additions & 2 deletions linkml_runtime/processing/validation_datamodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,8 @@ class ConstraintType(EnumDefinitionImpl):
)
MinCountConstraint = PermissibleValue(
text="MinCountConstraint",
description="cardinality constraint where the number of values of the slot must be greater or equal to a specified minimum",
description="cardinality constraint where the number of values of the slot must be greater than "
"or equal to a specified minimum",
meaning=SH.MinCountConstraintComponent,
)
RequiredConstraint = PermissibleValue(
Expand All @@ -420,7 +421,8 @@ class ConstraintType(EnumDefinitionImpl):
)
MaxCountConstraint = PermissibleValue(
text="MaxCountConstraint",
description="cardinality constraint where the number of values of the slot must be less than or equal to a specified maximum",
description="cardinality constraint where the number of values of the slot must be less than "
"or equal to a specified maximum",
meaning=SH.MaxCountConstraintComponent,
)
SingleValuedConstraint = PermissibleValue(
Expand Down
5 changes: 4 additions & 1 deletion linkml_runtime/utils/context_utils.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import json
import os
from io import TextIOWrapper
from typing import Any, Callable, Optional, Union
from typing import TYPE_CHECKING, Any, Callable, Optional, Union

import yaml
from jsonasobj2 import JsonObj, loads

if TYPE_CHECKING:
from linkml_runtime.utils.namespaces import Namespaces

CONTEXT_TYPE = Union[str, dict, JsonObj]
CONTEXTS_PARAM_TYPE = Optional[Union[CONTEXT_TYPE, list[CONTEXT_TYPE]]]

Expand Down
5 changes: 4 additions & 1 deletion linkml_runtime/utils/enumerations.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from dataclasses import fields
from typing import Optional, Union
from typing import TYPE_CHECKING, Optional, Union

from linkml_runtime.utils.metamodelcore import Curie
from linkml_runtime.utils.yamlutils import YAMLRoot

if TYPE_CHECKING:
from linkml_runtime.linkml_model import EnumDefinition, PermissibleValue


class EnumDefinitionMeta(type):
def __init__(cls, *args, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion linkml_runtime/utils/eval_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

def eval_conditional(*conds: list[tuple[bool, Any]]) -> Any:
"""
Evaluate a collection of expression,value tuples, returing the first value whose expression is true
Evaluate a collection of expression, value tuples, returning the first value whose expression is true
>>> x= 40
>>> eval_conditional((x < 25, 'low'), (x > 25, 'high'), (True, 'low'))
Expand Down
4 changes: 2 additions & 2 deletions linkml_runtime/utils/formatutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def wrapped_annotation(txt: str) -> str:
def shex_results_as_string(rslts) -> str:
"""Pretty print ShEx Evaluation result"""
# TODO: Add this method to ShEx itself
rval = [f"Evalutating: {str(rslts.focus)} against {str(rslts.start)}"]
rval = [f"Evaluating: {str(rslts.focus)} against {str(rslts.start)}"]
if rslts.result:
rval.append("Result: CONFORMS")
else:
Expand Down Expand Up @@ -158,7 +158,7 @@ def remove_empty_items(obj: Any, hide_protected_keys: bool = False, inside: bool
obj_list = [
e
for e in [
remove_empty_items(l, hide_protected_keys=hide_protected_keys, inside=True) for l in obj if l != "_root"
remove_empty_items(i, hide_protected_keys=hide_protected_keys, inside=True) for i in obj if i != "_root"
]
if not is_empty(e)
]
Expand Down
32 changes: 13 additions & 19 deletions linkml_runtime/utils/metamodelcore.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@
from linkml_runtime.utils.namespaces import Namespaces
from linkml_runtime.utils.strictness import is_strict
from linkml_runtime.utils.uri_validator import validate_curie, validate_uri, validate_uri_reference
from linkml_runtime.utils.yamlutils import TypedNode

# Reference Decimal to make sure it stays in the imports
_z = Decimal(1)

# ===========================
# Fields for use in dataclass
# ===========================
from linkml_runtime.utils.yamlutils import TypedNode


def empty_list():
Expand Down Expand Up @@ -233,13 +233,11 @@ def __new__(cls, value: Union[str, datetime.time, datetime.datetime, Literal]) -
if not isinstance(value, datetime.time):
value = datetime.time.fromisoformat(value)
return datetime.time.fromisoformat(str(value)).isoformat()
except TypeError:
pass
except ValueError:
pass
if not is_strict():
except (TypeError, ValueError):
if is_strict():
raise
finally:
return str(value)
raise e

@classmethod
def is_valid(cls, value: Union[str, datetime.time, datetime.datetime, Literal]) -> bool:
Expand All @@ -266,13 +264,11 @@ def __new__(cls, value: Union[str, datetime.date, Literal]) -> str:
if not isinstance(value, datetime.date):
value = datetime.date.fromisoformat(str(value))
return value.isoformat()
except TypeError:
pass
except ValueError:
pass
if not is_strict():
except (TypeError, ValueError):
if is_strict():
raise
finally:
return str(value)
raise e

@classmethod
def is_valid(cls, value: Union[str, datetime.date, Literal]) -> bool:
Expand Down Expand Up @@ -301,13 +297,11 @@ def __new__(cls, value: Union[str, datetime.datetime, Literal]) -> str:
if not isinstance(value, datetime.datetime):
value = datetime.datetime.fromisoformat(value) # Note that this handles non 'T' format as well
return value.isoformat()
except TypeError:
pass
except ValueError:
pass
if not is_strict():
except (TypeError, ValueError):
if is_strict():
raise
finally:
return str(value)
raise e

@classmethod
def is_valid(cls, value: Union[str, datetime.datetime, Literal]) -> bool:
Expand Down
8 changes: 4 additions & 4 deletions linkml_runtime/utils/permissiblevalueimpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,10 @@ class PvFormulaOptions(EnumDefinitionImpl):
description="The permissible values are the set of FHIR coding elements derived from the code set",
)

_defn = EnumDefinition(
name="PvFormulaOptions",
description="The formula used to generate the set of permissible values from the code_set values",
)
# _defn = EnumDefinition(
# name="PvFormulaOptions",
# description="The formula used to generate the set of permissible values from the code_set values",
# )


class PermissibleValueImpl(PermissibleValue):
Expand Down
6 changes: 3 additions & 3 deletions linkml_runtime/utils/schemaview.py
Original file line number Diff line number Diff line change
Expand Up @@ -1080,12 +1080,12 @@ def slot_is_true_for_metadata_property(self, slot_name: SlotDefinition, metadata
will return True if the slot id has the identifier property set to True.
:param slot_name: slot to test for multivalued
:param metadata_property: controlled vocabulary for boolean attribtues
:param metadata_property: controlled vocabulary for boolean attributes
:return: boolean
"""

induced_slot = self.induced_slot(slot_name)
if type(getattr(induced_slot, metadata_property)) == bool:
if type(getattr(induced_slot, metadata_property)) is bool:
return True if getattr(induced_slot, metadata_property) else False
else:
raise ValueError('property to introspect must be of type "boolean"')
Expand Down Expand Up @@ -1691,7 +1691,7 @@ def get_slots_by_enum(self, enum_name: ENUM_NAME = None) -> list[SlotDefinition]
"""Get all slots that use a given enum: schema defined, attribute, or slot_usage.
:param enum_name: enum in consideration
:return: list of slots, either schem or both class attribute defined
:return: list of slots, either schema or both class attribute defined
"""
enum_slots = []
for s in self.all_slots().values():
Expand Down
6 changes: 4 additions & 2 deletions notebooks/SchemaView_Monarch.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"\n",
"from linkml_runtime.utils.schemaview import SchemaView\n",
"import requests \n",
"\n",
"# note you can also use a path on a local filesystem\n",
"view = SchemaView(\"https://raw.githubusercontent.com/biolink/biolink-model/master/biolink-model.yaml\")"
]
Expand Down Expand Up @@ -90,7 +92,7 @@
"# object = 'phenotypic feature'\n",
"object = 'sequence variant'\n",
"\n",
"query_prefix = f'https://www.ebi.ac.uk/ols/api/ontologies/_ontology/terms/'\n",
"query_prefix = 'https://www.ebi.ac.uk/ols/api/ontologies/_ontology/terms/'\n",
"mappings = view.get_mappings(object)\n",
"if len(mappings) == 0:\n",
" print(\"no exact mappings found for: \" + object)\n",
Expand Down
3 changes: 2 additions & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import configparser
import logging

# Global testing control variables
import os
Expand Down Expand Up @@ -37,7 +38,7 @@


# There are lots of warnings emitted by the generators. Default logging level
DEFAULT_LOG_LEVEL = eval(test_settings.get("DEFAULT_LOG_LEVEL", "logging.ERROR"))
DEFAULT_LOG_LEVEL = getattr(logging, test_settings.get("DEFAULT_LOG_LEVEL", "WARNING"))
DEFAULT_LOG_LEVEL_TEXT = test_settings.get("DEFAULT_LOG_LEVEL_TEXT", "ERROR")


Expand Down
2 changes: 2 additions & 0 deletions tests/support/test_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,10 @@ def generate_single_file(
"""
# If no filter, default to identity function
if filtr is None:

def filtr(s):
return s

filename = filename if isinstance(filename, list) else [filename]
actual_file = self.root_temp_file_path(*filename) if use_testing_root else self.actual_path(*filename)
expected_file = self.root_expected_path(*filename) if use_testing_root else self.expected_path(*filename)
Expand Down
11 changes: 5 additions & 6 deletions tests/test_issues/input/issue_355.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@
# description:
# license: https://creativecommons.org/publicdomain/zero/1.0/

import dataclasses
from typing import Optional, Union, ClassVar, Any
from dataclasses import dataclass
from typing import Any, ClassVar, Optional, Union

from linkml_runtime.utils.slot import Slot
from linkml_runtime.utils.metamodelcore import empty_dict
from linkml_runtime.utils.yamlutils import YAMLRoot
from rdflib import URIRef

from linkml_runtime.utils.curienamespace import CurieNamespace
from linkml_runtime.utils.metamodelcore import URIorCURIE
from linkml_runtime.utils.metamodelcore import URIorCURIE, empty_dict
from linkml_runtime.utils.slot import Slot
from linkml_runtime.utils.yamlutils import YAMLRoot

metamodel_version = "1.7.0"

Expand Down
7 changes: 4 additions & 3 deletions tests/test_issues/input/issue_368.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
# description:
# license: https://creativecommons.org/publicdomain/zero/1.0/

import dataclasses
from typing import Optional, Union, ClassVar, Any
from dataclasses import dataclass
from typing import Any, ClassVar, Optional, Union

from linkml_runtime.utils.slot import Slot
from rdflib import URIRef

from linkml_runtime.utils.curienamespace import CurieNamespace
from linkml_runtime.utils.slot import Slot

from .issue_368_imports import ParentClass, SampleEnum

metamodel_version = "1.7.0"
Expand Down
9 changes: 4 additions & 5 deletions tests/test_issues/input/issue_368_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@
# description:
# license:

import dataclasses
from typing import ClassVar
from linkml_runtime.linkml_model.meta import EnumDefinition, PermissibleValue

from linkml_runtime.utils.yamlutils import YAMLRoot
from linkml_runtime.utils.enumerations import EnumDefinitionImpl
from rdflib import URIRef
from linkml_runtime.utils.curienamespace import CurieNamespace

from linkml_runtime.linkml_model.meta import EnumDefinition, PermissibleValue
from linkml_runtime.utils.curienamespace import CurieNamespace
from linkml_runtime.utils.enumerations import EnumDefinitionImpl
from linkml_runtime.utils.yamlutils import YAMLRoot

metamodel_version = "1.7.0"

Expand Down
2 changes: 1 addition & 1 deletion tests/test_loaders_dumpers/models/personinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from linkml_runtime.linkml_model.types import Decimal, Uri, Uriorcurie
from linkml_runtime.utils.curienamespace import CurieNamespace
from linkml_runtime.utils.enumerations import EnumDefinitionImpl
from linkml_runtime.utils.metamodelcore import Bool, Decimal, XSDDate, empty_dict, empty_list
from linkml_runtime.utils.metamodelcore import Bool, XSDDate, empty_dict, empty_list
from linkml_runtime.utils.slot import Slot
from linkml_runtime.utils.yamlutils import YAMLRoot, extended_str

Expand Down
Loading

0 comments on commit 23b8ea9

Please sign in to comment.