Type Casting¶
Here we describe the types that can be passed as the first argument to cast()
and their conversion rules.
In principle, all types must accept values of the same type as themselves. Therefore, this is not described repeatedly.
In the description, val
means the value passed as the second argument to cast()
.
If a type that is not directly supported is passed as the first argument of cast()
, the rules of the nearest base class are applied.
For example, a user-defined class that does not define a base class follows the rule of object
, and a class that inherits from int
follows the rule of int
.
So when we say we call int(val)
in the description of int
, you should interpret int
as being replaced by a user-defined type.
If the user-defined type does not follow the rules of the base class, it should be specialized with cast.register()
.
The same rules apply to val
.
For example, when we say enum.IntEnum
accepts int
in this description, it means accepts when isinstance(val, int)
is true.
If the user-defined type instance passed to val
doesn’t follow this rule, it can also be specialized with cast.register()
.
Builtin Types¶
Converted to and from
int
andstr
.When
bool
is converted tostr
, it is converted to"True"
or"False"
. When convertingstr
tobool
, convert it to lowercase first and then look up thebool_strings
dictionary. It raisesTypeError
if this dictionary is empty, andValueError
if it is not empty but there is no key for that string.If
bool_is_int
isFalse
, conversion to and fromint
is not allowed.If
lossy_conversion
isFalse
,int
other than 0 and 1 is not converted tobool
.One-way conversion from
bool
tofloat
is allowed. Iflossy_conversion
isFalse
, values other than 0 and 1 are not converted. Even this is forbidden ifbool_is_int
isFalse
.
Converted to and from
tuple[float,float]
andstr
.One-way conversion from
int
orfloat
tocomplex
is allowed.If
accept_nan
isFalse
, only values for whichcmath.isfinite()
returns true are accepted.
Converted to and from
int
,bool
,float
, andstr
.For other types, calls
int(val)
. This means that it accepts all user-defined types that support theint
conversion. In this case, the conversion in the opposite direction is up to the implementation of the user-defined type.If
bool_is_int
isFalse
thenbool
is not accepted.If
lossy_conversion
isFalse
, it does not acceptfloat
which has non-zero fractional part, and integers other than 0 and 1 are not converted tobool
.
Converted to and from
str
.When converting a type object to
str
, it is converted to fully qualified name. For builtin types, thebuiltins
module is used as the module name.When converting from
str
to a type object, it accepts fully qualified name. However, for builtin types, you can omitbuiltins
.If val is a type, only type checking is performed and val is returned as it is.
Given a generic type parameter, it is interpreted as covariant. In other words, it accepts all subclasses of the type parameter.
In addition to
TypeError
,ImportError
orAttributeError
can also be raised.
Standard Types¶
enum
¶
Converted to and from
int
using value of enum member.Unlike
enum.IntEnum
, conversion to and fromstr
is not supported.
typing
¶
A type
T
can be annotated with metadatax
via the typehintAnnotated[T, x]
.If
x
is an instance ofConstraint
, thencast()
checks if the value after casting meets the constraint defined byx
. Also, this constraint is reflected inJsonSchema
.If multiple metadata is provided, all constraints must be satisfied.
Ignored if
x
is not an instance ofConstraint
.Since
typing.Annotated
was added in Python 3.9, thetypeable.typing
module provides backport.Currently Typeable provides the following
Constraint
subclasses:
AllOf
,AnyOf
,NoneOf
,IsFinite
,IsGreaterThan
,IsGreaterThanOrEqual
,IsLessThan
,IsLessThanOrEqual
,IsLongerThanOrEqual
,IsMatched
,IsMultipleOf
, andIsShorterThanOrEqual
.
Pass
val
as it is without conversion or checking.
typing.ForwardRef
that appears in the type parameter of a generic type is automatically evaluated by Typeable.
typing.ForwardRef
does not express a type by itself, it is just an intermediary passing a string forward reference to delay evaluation of a type. Usually (though not impossible) you don’t create an instance oftyping.ForwardRef
yourself, it is created automatically when you pass a string to the type parameter when using a generic type. The support provided by thetyping
module is limited to the annotation area.Typeable provides a
declare()
context manager so that forward references can be used outside of the annotation.
If there is a literal that matches
val
, it returns the literal, otherwiseValueError
is raised.Since
typing.Literal
was added in Python 3.8, thetypeable.typing
module provides backport.
typing.Optional
is automatically converted totyping.Union
.
Same as the conversion rule for
type
.
Typeable Types¶
A subclass of
Object
representing JSON Schema.
Converted to and from
dict
.When
dict
is converted toObject
, undefined keys are ignored. It raisesTypeError
if a field with required specified asTrue
is missing. If the field specifying default_factory is missing, it creates a value and assigns it to the instance attribute.When
Object
is converted todict
, onlyObject
instance attributes are provided. Fields not assigned to instance attributes are not included. Although default is defined so the attribute can be read, it will not be included if it has not been assigned as an instance attribute.