Skip to content

Commit

Permalink
cast is working!!!
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoGorelli committed Feb 23, 2024
1 parent 4f5fad2 commit dfe3954
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 5 deletions.
5 changes: 4 additions & 1 deletion narwhals/pandas_like/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,10 @@ def from_column_names(
implementation=implementation,
)

def cast(self, dtype: DType) -> Self: # type: ignore[override]
def cast(
self,
dtype: DType, # type: ignore[override]
) -> Self:
return register_expression_call(self, "cast", dtype)

def __eq__(self, other: Expr | Any) -> Self: # type: ignore[override]
Expand Down
32 changes: 28 additions & 4 deletions narwhals/pandas_like/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,12 +359,36 @@ def translate_dtype(dtype: Any) -> DType:
raise TypeError(msg)


def reverse_translate_dtype(dtype: DType) -> Any:
def isinstance_or_issubclass(obj: Any, cls: Any) -> bool:
return isinstance(obj, cls) or issubclass(obj, cls)


def reverse_translate_dtype(dtype: DType | type[DType]) -> Any:
from narwhals.pandas_like import dtypes

if isinstance(dtype, dtypes.Int64):
return "int64"
if isinstance(dtype, dtypes.Float32) or issubclass(dtype, dtypes.Float32):
if isinstance_or_issubclass(dtype, dtypes.Float64):
return "float64"
if isinstance_or_issubclass(dtype, dtypes.Float32):
return "float32"
if isinstance_or_issubclass(dtype, dtypes.Int64):
return "int64"
if isinstance_or_issubclass(dtype, dtypes.Int32):
return "int32"
if isinstance_or_issubclass(dtype, dtypes.Int16):
return "int16"
if isinstance_or_issubclass(dtype, dtypes.UInt8):
return "uint8"
if isinstance_or_issubclass(dtype, dtypes.UInt64):
return "uint64"
if isinstance_or_issubclass(dtype, dtypes.UInt32):
return "uint32"
if isinstance_or_issubclass(dtype, dtypes.UInt16):
return "uint16"
if isinstance_or_issubclass(dtype, dtypes.UInt8):
return "uint8"
if isinstance_or_issubclass(dtype, dtypes.String):
return "object"
if isinstance_or_issubclass(dtype, dtypes.Bool):
return "bool"
msg = f"Unknown dtype: {dtype}"
raise TypeError(msg)
3 changes: 3 additions & 0 deletions narwhals/spec/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ class Expr(Protocol):
def alias(self, name: str) -> Self:
...

def cast(self, dtype: DType) -> Self:
...

def __and__(self, other: Any) -> Expr:
...

Expand Down

0 comments on commit dfe3954

Please sign in to comment.