I'm trying to get the source, callee list, defaults, keywords, args and varargs of the functions in a python script.
Currently, I'm importing the module and using the python inspect
module's getmembers
function and passing the isfunction
parameter like so:
members = inspect.getmembers(myModule, inspect.isfunction)
However, this method doesn't work if myModule
's imports aren't available to me (since myModule
has to be imported first).
I tried using the python ast
module to parse
and dump
the syntax tree, but getting the function source involved very hacky techniques and/or questionable and far from maintainable third party libraries. I believe I've scoured the documentation and stackoverflow pretty thoroughly and have failed to find a suitable solution. Am I missing something?
So I looked around some more and quickly Frankenstein'd a solution using this dude's answer to get each function's source. It isn't anywhere near perfect yet, but here it is if you're interested:
Output:
A possible workaround is to monkeypatch the
__import__
function with a custom function that never throws an ImportError and returns a dummy module instead:This would allow you to import
myModule
even if its dependencies cannot be imported. Then you can useinspect.getmembers
as you normally would:A problem with this solution is that it only works around the failing imports. If
myModule
tries to access any members of the imported modules, its import will fail:In order to work around this, you can create a dummy class that never throws an AttributeError:
(See the data model documentation for a list of dunder methods you may have to implement.)
Now if
force_import
returns an instance of this class (changereturn builtins
toreturn DummyValue()
), importingmyModule
will succeed.