Reputation: 8072
I want to know if a function/class exists somewhere in a module.
I do know how to generate a list of all the classes/functions that are at the upper level/hierarchy of the module using dir()
For example, let's say I want to know if function now()
exists inside the datetime
module:
import datetime
dir(datetime)
But this does not list the function now()
because now()
is contained in a deeper level (in datetime.datetime
to be exact). How do I check if now()
exists or not?
Or maybe there is a way to list everything from all the levels?
Upvotes: 2
Views: 132
Reputation: 159
This piece of code lists the contents of modules recursively. Note however it will fail if two submodules/objects/... share the same name
import time
import datetime
pool=[] # to avoid loops
def recdir(d,n=''):
children_all=dir(d)
children=[c for c in children_all if c[0]!='_' and not c in pool]
for child in children:
pool.append(child)
full_name=n+"."+child
print "Found: ","'"+full_name+"' type=",eval("type("+full_name+")")
string="recdir(d."+child+",'"+full_name+"')"
print "Evaluating :",string
time.sleep(0.2)
eval(string)
recdir(datetime,'datetime')
Upvotes: 1