# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_cast.ipynb.

# %% auto 0
__all__ = ['T', 'cast', 'caster']

# %% ../nbs/00_cast.ipynb 6
from functools import wraps

# %% ../nbs/00_cast.ipynb 8
from typing import Any, Union, TypeVar
T = TypeVar('T')

# %% ../nbs/00_cast.ipynb 10
#| export


# %% ../nbs/00_cast.ipynb 12
#| export


# %% ../nbs/00_cast.ipynb 14
#| export


# %% ../nbs/00_cast.ipynb 16
def cast(x, dtype: T, retnone: bool = False) -> Union[T, Any, None]:
    '''Tries to cast `x` to `dtype`. If `retnone` is `True`, returns `None` if the cast fails, otherwise returns `x`.'''
    try: return dtype(x)
    except: return None if retnone else x


def caster(dtype: T, retnone: bool = False):
    def decorator(func):
        @wraps(func)
        def wrapper(x, retnone: bool = retnone) -> Union[T, Any, None]:
            return cast(x, dtype, retnone)
        return wrapper
    return decorator
