Background:
Migrating from R to Python with numpy/scipy. Trying to make a little module of useful functions. In particular, I’m trying to create a recursive element-type checker.
Question:
Is it possible to get a list of the current valid types in the Python environment a function is being called in?
For example, isinstance(1,int) will return True, isinstance(1,str) will return False, but isinstance(1,asdf) will throw a NameError: name 'asdf' is not defined i.e. int and str are defined, but asdf is not. How can I get the list of types that are defined, or names present in the current Python environment, and filter them by types?
In Python, types are themselves ordinary objects. That is, for example,
are all
True.So to do this, look for all variables in scope that point to objects of type
type.To get all objects in scope, look at
bothdir()(which excludes built-in names likeint) anddir(__builtins__)(the built-in names)locals()(variables defined in the current function),globals()(variables defined outside of functions in the current module), andvars(__builtins__)(the built-in names). These are all dictionaries from name => object, so combine them all and get the objects:and filter only types:
Note that these are just the variables in scope that point to types. It’s quite possible to have a reference to an object whose type is not assigned to any variable in scope. For example: