Description
What happened?
This is a cross-post from the @beartype issue tracker, in which a downstream user tried to apply runtime type checking while using xarray... only to discover all the types, at runtime, were non-existent. The chief cause of this is spurious usage of if TYPE_CHECKING
used throughout the xarray repo, which is undefined at runtime, like the types it provides.
beartype/beartype#456
The below bug report is merely copied from that post.
The relevant issue (with respect to the MCVE below) seems to be the below example from the code base:
from __future__ import annotations
from typing import IO, TYPE_CHECKING, Any, Generic, Literal, cast, overload
...
if TYPE_CHECKING:
...
from xarray.core.dataarray import DataArray # Crucially missing at runtime
...
class Dataset(
DataWithCoords,
DatasetAggregations,
DatasetArithmetic,
Mapping[Hashable, "DataArray"], # Terribly undefined at runtime
):
What did you expect to happen?
For the types to be visible at runtime, for runtime type checking.
From @leycec, the only real change needed should be:
class Dataset(
DataWithCoords,
DatasetAggregations,
DatasetArithmetic,
Mapping[Hashable, "xarray.core.dataarray.DataArray"], # <-- this is all @beartype asks
):
Minimal Complete Verifiable Example
import xarray as xr
from beartype import beartype
@beartype
def process_data(data: xr.Dataset):
print(f"Processing data of type: {type(data)}")
ds = xr.Dataset({"temperature": (["x", "y"], [[20, 25], [30, 35]])})
process_data(ds) # This fails
MVCE confirmation
- Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
- Complete example — the example is self-contained, including all data and the text of any traceback.
- Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
- New issue — a search of GitHub Issues suggests this is not a duplicate.
- Recent environment — the issue occurs with the latest version of xarray and its dependencies.
Relevant log output
On the `# this fails` line:
BeartypeCallHintForwardRefException: Forward reference \"DataArray\" unimportable from module \"__main__\"."
Anything else we need to know?
MVCE Versions
beartype: 0.19.0
xarray: 2024.9.0
Python: 3.11.10
Environment
Omitted the environment, because not relevant.