This is a memo of how to implement the function ʻis_type_factory to create the function ʻis_y (x)
that will cause an error if the type of the variable x
is not y
for multiple types as follows.
config.py
is_int = is_type_factory(int)
is_bool = is_type_factory(bool)
is_float = is_type_factory(float)
is_str = is_type_factory(str)
is_unicode = is_type_factory(compat.text_type)
is_text = is_instance_factory((str, bytes))
[pandas] I saw it in the source (https://github.com/pandas-dev/pandas/blob/master/pandas/core/config.py).
Nesting function definitions is an example of how to use it this way. The argument _type
passed to ʻis_type_factory acts as a static variable in the returned function object ʻinner
.
config.py
def is_type_factory(_type):
"""
Parameters
----------
`_type` - a type to be compared against (e.g. type(x) == `_type`)
Returns
-------
validator - a function of a single argument x , which returns the
True if type(x) is equal to `_type`
"""
def inner(x):
if type(x) != _type:
raise ValueError("Value must have type '%s'" % str(_type))
return inner