"""Helper functions for validation of dtype.For literal dtypes intended for use by end-users, see :mod:`numpydantic.dtype`"""importsysfromtypingimportAny,Union,get_args,get_originimportnumpyasnpfromnumpydantic.typesimportDtypeTypeifsys.version_info>=(3,10):fromtypesimportUnionTypeelse:UnionType=None
[docs]defvalidate_dtype(dtype:Any,target:DtypeType)->bool:""" Validate a dtype against the target dtype Args: dtype: The dtype to validate target (:class:`.DtypeType`): The target dtype Returns: bool: ``True`` if valid, ``False`` otherwise """iftargetisAny:returnTrueifisinstance(target,tuple):valid=dtypeintargetelifis_union(target):valid=any([validate_dtype(dtype,target_dt)fortarget_dtinget_args(target)])eliftargetisnp.str_:valid=getattr(dtype,"type",None)in(np.str_,str)ordtypein(np.str_,str,)else:# try to match as any subclass, if target is a classtry:valid=issubclass(dtype,target)exceptTypeError:# expected, if dtype or target is not a classvalid=dtype==targetreturnvalid
[docs]defis_union(dtype:DtypeType)->bool:""" Check if a dtype is a union """ifUnionTypeisNone:returnget_origin(dtype)isUnionelse:returnget_origin(dtype)in(Union,UnionType)