Reputation: 378
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?
Upvotes: 2
Views: 1634
Reputation: 30647
In Python, types are themselves ordinary objects. That is, for example,
type('hello') == str
type(5) == int
type(int) == type
type(type) == type
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 both dir()
(which excludes built-in names like int
) and dir(__builtins__)
(the built-in names)locals()
(variables defined in the current function), globals()
(variables defined outside of functions in the current module), and vars(__builtins__)
(the built-in names). These are all dictionaries from name => object, so combine them all and get the objects:
objs = dict(vars(__builtins__), **dict(globals(), **locals())).values()
and filter only types:
types_in_scope = [o for o in objs if isinstance(o, type)]
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:
def foo():
class Foo:
pass
return Foo()
x = foo()
Upvotes: 2
Reputation:
Maybe you could look up the types
module? Please see the documentation here: http://docs.python.org/library/types.html. And you may also get the current variables in your program, like so:
In [9]: def spam():
x=5
y=6
In [10]: spam.func_code.co_varnames
Out[10]: ('x', 'y')
Hope it helps and you can get started. Sorry, if I totally went off track.
Upvotes: 0