How to find the code of a function in a module [solved w/ inspect]

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • thessjshawn
    New Member
    • Sep 2006
    • 2

    How to find the code of a function in a module [solved w/ inspect]

    I am creating a program that will allow the user to input "code" and then the name of a function for a program. What sort of code will allow me to search through the program for the name of the function and then print out the code of the function to the user?

    Thanks
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    This aught to do the trick


    Code:
    import inspect
    
    def function():
        pass
    
    def func1():
        print "func1"
    
    def func2():
        print "func2"
        return 0
    
    def find_function(funcname):
        """I cheated on fuction type compare because I was too busy to find out
        what the actual type a function is, but this works"""
    
        code = None
        for key, item in globals().items():
            if type(item) == type(function):
                if key == funcname:
                    code = inspect.getsourcelines(item)
        return code
    
    lines_of_code = find_function("func2")
    
    if lines_of_code:
        for line in lines_of_code[0]:
            print line,

    Comment

    Working...