cape.tnakit.typeutils: Python 2/3 type-check utils

This module contains convenience methods to check types of objects. For the most part, this is a set of predefined calls to isinstance(), but with several groups of objects. Furthermore, it contains several aspects that help address differences between Python 2 and 3. For example, it defines the unicode class for Python 3 by simply setting it equal to str.

cape.tnakit.typeutils.isarray(x)

Check if a variable is a list or similar

Accepted types are list, numpy.ndarray, tuple, or any subclass thereof.

Call:
>>> q = isarray(x)
Inputs:
x: any

Any variable

Outputs:
q: True | False

Whether or not x is of type list, tuple, np.ndarray, or any subclass of these three

Versions:
  • 2019-03-04 @ddalle: First version

cape.tnakit.typeutils.isfile(f)

Check if an object is an instance of a file-like class

This is complicated by the removal of the file type from Python 3. The basic class is io.IOBase, but this is not a subclass of file (or vice versa) in Python 2.

Call:
>>> q = isfile(f)
Inputs:
f: any

Any variable

Outputs:
q: True | False

Whether or not f is an instance of file, io.IOBase, or any subclass

Versions:
  • 2019-12-06 @ddalle: First version

cape.tnakit.typeutils.isinstancen(x, types)

Special version of isinstance() that allows None

Call:
>>> q = isinstance(x, types)
Inputs:
x: any

Any value

types: type | tuple[type]

Type specification as for isinstance()

Outputs:
q: True | False

True if x is None or isinstance(x, types)

Versions:
  • 2020-01-13 @ddalle: First version

cape.tnakit.typeutils.isstr(x)

Check if a variable is a string (or derivative)

Call:
>>> q = isstr(x)
Inputs:
x: any

Any variable

Outputs:
q: True | False

Whether or not x is of type str or unicode or any subclass thereof (and averting disaster caused by lack of unicode class in Python 3+)

Versions:
  • 2019-03-04 @ddalle: First version