Skip to content
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
33 changes: 26 additions & 7 deletions src/arcadedb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,41 @@
# silently. Refuse to import when the other one is installed too, before anything else runs.
_check_distributions(_DISTRIBUTION_BACKEND)


# The installed distribution's version is the single source of truth: the
# wheel is versioned from the release tag, while the generated _version.py
# is derived from the engine jar's version (scripts/write_version.py), so the
# two disagree on tagged releases
# (a 26.8.1.dev20 wheel carried __version__ == "26.8.1.dev0"). Fall back to
# the generated file, then to a placeholder, for source checkouts that were
# never installed.
try:
from importlib.metadata import version as _dist_version
# importlib.metadata costs about 30 ms to import, so the version is read on the first access of arcadedb.__version__ (#477).
# The bare annotation (no value, so nothing is created at import) tells a type checker the name exists and is a str; the module
# __getattr__ below fills it in.
__version__: str

__version__ = _dist_version(_DISTRIBUTIONS[_DISTRIBUTION_BACKEND])
except Exception: # not installed: fall back to the build-time file

def _read_version() -> str:
try:
from ._version import __version__
except ModuleNotFoundError:
__version__ = "0.0.0"
from importlib.metadata import version as _dist_version

return _dist_version(_DISTRIBUTIONS[_DISTRIBUTION_BACKEND])
except Exception: # not installed: fall back to the build-time file
try:
from ._version import __version__ as built

return built
except ModuleNotFoundError:
return "0.0.0"


def __getattr__(name: str) -> str:
if name == "__version__":
value = _read_version()
globals()["__version__"] = value
return value
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


# Import async execution
from .async_executor import AsyncExecutor # noqa: E402
Expand Down
70 changes: 64 additions & 6 deletions src/arcadedb/_dist_conflict.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@

from __future__ import annotations

from importlib import metadata
from typing import Callable
import os
import sys
from typing import Callable, Optional

# backend -> the distribution that carries it
DISTRIBUTIONS = {"native": "arcadedb", "jvm": "arcadedb-jvm"}
Expand All @@ -33,20 +34,77 @@ def other_backend(backend: str) -> str:
return "jvm" if backend == "native" else "native"


def _package_not_found():
"""``importlib.metadata.PackageNotFoundError``; the module costs about 30 ms to import, so it is imported only when it is needed."""
from importlib import metadata

return metadata.PackageNotFoundError


def _dist_info_present(name: str) -> Optional[bool]:
"""Whether a ``<name>-<version>.dist-info`` (or ``.egg-info``) directory is on ``sys.path``; None when this cannot say.

This is what ``importlib.metadata.version`` finds for an ordinary install, without importing it. A ``sys.path`` entry that is
not a directory (a zip, an egg file) is the case it does not read, so it returns None and the caller asks ``importlib.metadata``.
"""
stem = name.replace("-", "_").lower()
prefix = stem + "-"
for entry in sys.path:
try:
names = os.listdir(entry or ".")
except NotADirectoryError:
return None
except (
OSError
): # a missing or unreadable directory: importlib.metadata skips it too
continue
for item in names:
low = item.lower()
if low in (stem + ".egg-info", stem + ".dist-info"):
return True
if (
low.startswith(prefix)
and low[len(prefix) : len(prefix) + 1].isdigit()
and low.endswith((".dist-info", ".egg-info"))
):
return True
return False


def _lookup_by_metadata(name: str) -> str:
from importlib import metadata

return metadata.version(name)


def installed(
backends: tuple[str, ...] = ("native", "jvm"),
lookup: Callable[[str], str] = metadata.version,
lookup: Optional[Callable[[str], str]] = None,
) -> list[str]:
"""The distribution names of `backends` that are installed, in the order given.

`lookup` raises `importlib.metadata.PackageNotFoundError` for a name that is not installed.
`lookup` raises `importlib.metadata.PackageNotFoundError` for a name that is not installed. Without one, the distribution
directories on `sys.path` are read directly, which does not import `importlib.metadata`.
"""
found = []
for backend in backends:
name = DISTRIBUTIONS[backend]
if lookup is None:
present = _dist_info_present(name)
if (
present is None
): # a zip or an egg on sys.path: let importlib.metadata read it
try:
_lookup_by_metadata(name)
except _package_not_found():
continue
present = True
if present:
found.append(name)
continue
try:
lookup(name)
except metadata.PackageNotFoundError:
except _package_not_found():
continue
found.append(name)
return found
Expand All @@ -67,7 +125,7 @@ def message(backend: str) -> str:
)


def check(backend: str, lookup: Callable[[str], str] = metadata.version) -> None:
def check(backend: str, lookup: Optional[Callable[[str], str]] = None) -> None:
"""Raise DistributionConflictError when the distribution of the other backend is installed too.

Never raises for anything else: an import must not fail because the metadata could not be read.
Expand Down
77 changes: 77 additions & 0 deletions src/arcadedb/_lazy_numpy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""numpy without paying for it at ``import arcadedb``.

NumPy is optional, and importing it costs about 60 ms. The modules used to do ``import numpy as _np`` (or ``_np = None`` without it)
at the top, so every ``import arcadedb`` paid for it, also in a process that never touches an array. ``lazy_numpy()`` gives them the
same ``_np`` name with the same two properties, and imports the real module on first use:

* ``_np is None`` exactly when NumPy is not installed (a ``find_spec`` lookup, no import), so every ``if _np is None`` fallback
(the standard-library float32 tail of the native reply reader, the column builders) behaves as before.
* ``_np.ndarray``, ``_np.generic``, ``_np.floating`` and ``_np.dtype`` are only ever used to ask whether a value the caller passed in
is a NumPy object. While NumPy is not imported in the process, no such value can exist, so the answer is a class nothing is an
instance of, and nothing is imported. Once the process has numpy, these are the real classes.
* Every other attribute (``_np.asarray``, ``_np.float32``, ``_np.fromiter`` ...) is a call that builds or reads an array: it imports
NumPy on the first use and is then a plain instance attribute.
"""

from __future__ import annotations

import sys
from importlib.util import find_spec
from typing import Any, Optional

# Used only in isinstance() and issubclass() on a caller's value (see the module docstring). Every other name is always the real one.
_VALUE_TESTS = frozenset({"ndarray", "generic", "floating", "dtype"})


def _stand_in(name: str) -> type:
"""Stands for the NumPy class ``name`` while NumPy is not imported: nothing is an instance and nothing is a subclass.

Called like the class (``_np.dtype("datetime64[ns]")``), it imports NumPy and builds the real object.
"""

def __new__(cls, *args: Any, **kwargs: Any) -> Any:
import numpy

return getattr(numpy, name)(*args, **kwargs)

return type(f"_NoValueIs_{name}", (), {"__new__": __new__})


_STAND_INS = {name: _stand_in(name) for name in _VALUE_TESTS}


class _LazyNumpy:
"""The ``_np`` name of a module, until a call needs the real NumPy."""

def __getattr__(self, name: str) -> Any:
# only reached for a name this object does not hold yet
module = sys.modules.get("numpy")
if name in _VALUE_TESTS:
if module is None:
return _STAND_INS[
name
] # not cached: the process may import numpy later
value = getattr(module, name)
else:
if module is None:
import numpy as module
value = getattr(module, name)
object.__setattr__(
self, name, value
) # the next access is an ordinary attribute read
return value


_LAZY = _LazyNumpy()
_HAS_NUMPY: Optional[bool] = None


def lazy_numpy() -> Optional[_LazyNumpy]:
"""``None`` when NumPy is not installed, else the lazy stand-in for the ``numpy`` module."""
global _HAS_NUMPY
if _HAS_NUMPY is None:
try:
_HAS_NUMPY = find_spec("numpy") is not None
except (ImportError, ValueError):
_HAS_NUMPY = False
return _LAZY if _HAS_NUMPY else None
11 changes: 5 additions & 6 deletions src/arcadedb/_native/codec.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
from datetime import date, datetime, timezone
from decimal import Decimal

try: # numpy is optional
import numpy as _np
except ImportError: # pragma: no cover
_np = None
from .._lazy_numpy import lazy_numpy # noqa: E402

# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477)
_np = lazy_numpy()

TAG = "\u0001"
_TAG_ESCAPED = "\\u0001" # TAG as it appears in reply text: NativeCodec.quote writes it as a \u escape
Expand Down Expand Up @@ -337,7 +337,6 @@ def encode_vertex_args(type_name, rows, names, matrices):


_INT64_MAX = 2**63 - 1
_NS_DATETIME = None if _np is None else _np.dtype("datetime64[ns]")


def sample_array(values, timestamps=False):
Expand Down Expand Up @@ -367,7 +366,7 @@ def sample_array(values, timestamps=False):
if timestamps or dtype.itemsize > 8:
return None
return _np.ascontiguousarray(values, dtype=_np.float64)
if kind == "M" and timestamps and dtype == _NS_DATETIME:
if kind == "M" and timestamps and dtype == _np.dtype("datetime64[ns]"):
counts = _np.ascontiguousarray(values.view(_np.int64))
if (
counts == _np.iinfo(_np.int64).min
Expand Down
7 changes: 3 additions & 4 deletions src/arcadedb/_native/columnar.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,13 @@
from datetime import date, datetime, timezone
from decimal import Decimal

from .._lazy_numpy import lazy_numpy # noqa: E402
from .schema_objects import ( # the schema-entry reader shared with NativeType (#195)
_name_type,
)

try:
import numpy as _np
except ImportError: # pragma: no cover
_np = None
# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477)
_np = lazy_numpy()

_INT64_MAX = 2**63 - 1
_INT32_MAX = 2**31 - 1
Expand Down
7 changes: 3 additions & 4 deletions src/arcadedb/_native/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@
from pathlib import Path

from .. import _logdir
from .._lazy_numpy import lazy_numpy # noqa: E402
from ..exceptions import ArcadeDBError

try: # numpy is optional (the extra arcadedb[numpy]): without it the float32 tail is read with the standard library
import numpy as _np
except ImportError: # pragma: no cover
_np = None
# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477)
_np = lazy_numpy()

_LIB_NAMES = {
"linux": "libarcadedb.so",
Expand Down
16 changes: 10 additions & 6 deletions src/arcadedb/_native/schema_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
vector index wrapper over ``vectorNeighbors``. Read-only views: DDL stays SQL statements.
"""

import functools
import json
import re

Expand All @@ -23,11 +24,14 @@
_RID_PAIRS = re.compile(r"#\d{1,9}:\d{1,18}(?:;#\d{1,9}:\d{1,18})*")
_DIGITS = re.compile(r"\d+")
_NUMBERS = frozenset((float, int))
_FLOAT_DTYPES = (
(_np.dtype(_np.float16), _np.dtype(_np.float32), _np.dtype(_np.float64))
if _np is not None
else ()
)


@functools.cache
def _float_dtypes():
"""The float dtypes a query vector may have; only called with a numpy array in hand, so numpy is imported by then."""
return (_np.dtype(_np.float16), _np.dtype(_np.float32), _np.dtype(_np.float64))


# an int up to this is a double, so float32 rounds it as Java's floatValue() of the parsed JSON number does
_EXACT_INT = 1 << 53

Expand Down Expand Up @@ -203,7 +207,7 @@ def _vindex_query(query_vector):
if _np is None:
return None
if type(query_vector) is _np.ndarray:
if query_vector.ndim != 1 or query_vector.dtype not in _FLOAT_DTYPES:
if query_vector.ndim != 1 or query_vector.dtype not in _float_dtypes():
return None
source = query_vector
elif type(query_vector) in (list, tuple):
Expand Down
8 changes: 4 additions & 4 deletions src/arcadedb/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,10 @@ def _warn_no_commit_witness(what):
_LOGGER.debug("Cannot read the transaction commit %s", what, exc_info=True)


try: # optional; hoisted to module scope to keep it out of per-call hot paths
import numpy as _np
except ImportError: # pragma: no cover - numpy is an optional dependency
_np = None
from ._lazy_numpy import lazy_numpy # noqa: E402

# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477)
_np = lazy_numpy()

# Java class handles resolved once per process (jpype.JClass lookups are not
# free and used to run per record in wrapper dispatch).
Expand Down
8 changes: 4 additions & 4 deletions src/arcadedb/type_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@

import jpype

try:
import numpy as _np
except ImportError: # numpy is optional
_np = None
from ._lazy_numpy import lazy_numpy # noqa: E402

# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477)
_np = lazy_numpy()


class _JavaTimeTypes(NamedTuple):
Expand Down
7 changes: 3 additions & 4 deletions src/arcadedb/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@
import jpype
import jpype.types as jtypes

from ._lazy_numpy import lazy_numpy # noqa: E402
from .exceptions import ArcadeDBError

if TYPE_CHECKING:
from .core import Database

try: # optional; hoisted to module scope to keep it out of per-call hot paths
import numpy as _np
except ImportError: # pragma: no cover - numpy is an optional dependency
_np = None
# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477)
_np = lazy_numpy()


def _quote_identifier(identifier: str) -> str:
Expand Down
Loading
Loading