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
intandstr.When
boolis converted tostr, it is converted to"True"or"False". When convertingstrtobool, convert it to lowercase first and then look up thebool_stringsdictionary. It raisesTypeErrorif this dictionary is empty, andValueErrorif it is not empty but there is no key for that string.If
bool_is_intisFalse, conversion to and fromintis not allowed.If
lossy_conversionisFalse,intother than 0 and 1 is not converted tobool.One-way conversion from
booltofloatis allowed. Iflossy_conversionisFalse, values other than 0 and 1 are not converted. Even this is forbidden ifbool_is_intisFalse.
Converted to and from
tuple[float,float]andstr.One-way conversion from
intorfloattocomplexis allowed.If
accept_nanisFalse, 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 theintconversion. In this case, the conversion in the opposite direction is up to the implementation of the user-defined type.If
bool_is_intisFalsethenboolis not accepted.If
lossy_conversionisFalse, it does not acceptfloatwhich 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, thebuiltinsmodule is used as the module name.When converting from
strto 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,ImportErrororAttributeErrorcan also be raised.
Standard Types¶
enum¶
Converted to and from
intusing value of enum member.Unlike
enum.IntEnum, conversion to and fromstris not supported.
typing¶
A type
Tcan be annotated with metadataxvia the typehintAnnotated[T, x].If
xis 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
xis not an instance ofConstraint.Since
typing.Annotatedwas added in Python 3.9, thetypeable.typingmodule provides backport.Currently Typeable provides the following
Constraintsubclasses:
AllOf,AnyOf,NoneOf,IsFinite,IsGreaterThan,IsGreaterThanOrEqual,IsLessThan,IsLessThanOrEqual,IsLongerThanOrEqual,IsMatched,IsMultipleOf, andIsShorterThanOrEqual.
Pass
valas it is without conversion or checking.
typing.ForwardRefthat appears in the type parameter of a generic type is automatically evaluated by Typeable.
typing.ForwardRefdoes 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.ForwardRefyourself, it is created automatically when you pass a string to the type parameter when using a generic type. The support provided by thetypingmodule 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, otherwiseValueErroris raised.Since
typing.Literalwas added in Python 3.8, thetypeable.typingmodule provides backport.
typing.Optionalis automatically converted totyping.Union.
Same as the conversion rule for
type.
Typeable Types¶
A subclass of
Objectrepresenting JSON Schema.
Converted to and from
dict.When
dictis converted toObject, undefined keys are ignored. It raisesTypeErrorif a field with required specified asTrueis missing. If the field specifying default_factory is missing, it creates a value and assigns it to the instance attribute.When
Objectis converted todict, onlyObjectinstance 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.