(for the purpose of better understanding the structure of package)
Let's say we have some package/module (say, somemodule
), with the following structure:
somemodule
-- file1.py
fo(x) # a function
-- file2.py
bar(x) # a function
-- dir1
---- file3.py
A # a class
fun(y) # some method
_bo(y) # some "hidden" method
I would like some output like:
path name type
/file1.py fo(x) function
/file2.py bar(x) function
/dir1/file3.py A class
/dir1/file3.py A.fun(y) method
/dir1/file3.py A._bo(y) method
Given that I'm a novice in Python, I have no idea how to go about constructing such information, and would be happy for help.
The closest I found online was:
- How to list all functions in a module? - which didn't help enough, since it only shows some functions (not the hidden ones), doesn't show methods within classes, and doesn't show file path (i.e.: neither dir, or help, or some of the other suggested functions seem to be up to the task).
- How do I list all files of a directory? - shows files, but not for a module (not the functions/classes/methods within the object)
CodePudding user response:
Heres an example on how to do it:
import inspect
import TestModule
def recusive_module_search(module):
members = inspect.getmembers(module)
for name, member in members:
if inspect.ismodule(member):
# Dont go too deep :)
if member is module:
recusive_module_search(member)
elif inspect.isfunction(member):
file = inspect.getfile(member)
print(file, function_signature_string(member), "function")
elif inspect.isclass(member):
file = inspect.getfile(member)
print(file, function_signature_string(member), "class")
class_members = inspect.getmembers(member)
for name, class_member in class_members:
if inspect.isfunction(class_member):
member_args = inspect.signature(class_member)
print(file, member.__name__ "." function_signature_string(class_member), "method")
def function_signature_string(member):
parameters = inspect.signature(member).parameters
return member.__name__ "(" ', '.join(str(x) for x in parameters.values()) ")"
recusive_module_search(TestModule)
output:
C:\Users\mclea\src\PydanticMongoEngine\TestModule\functions.py Test(x: int, y: float) class
C:\Users\mclea\src\PydanticMongoEngine\TestModule\functions.py Test.__init__(self, x: int, y: float) method
C:\Users\mclea\src\PydanticMongoEngine\TestModule\functions.py Test.print_x(self) method
C:\Users\mclea\src\PydanticMongoEngine\TestModule\functions.py hi(x: int) function
C:\Users\mclea\src\PydanticMongoEngine\TestModule\SubModule\test.py test_fn(hello: str) function
Continue as desired :)
CodePudding user response:
try dir(module) if there are sub modules you have to iterate and traverse in all classes