Search code examples
pythonfunctionpython-3.xcallstackcall-graph

How to print graph call as tree?


For instanse, I have the following code snippet:

def func1(num):
    print(num)

def func2(num):
    func1(num)

def func3(num):
    func2(num)
    func1(num)

def begin():
    pass

def print_graph():
    pass


def main():
    begin()
    func3(3)
    print_graph()

Is there any simple way to print something like that:

func3(1)
    func2(1)
        func1(1)
    func1(1)

I believe, that I have to use globals(), but I don't know, what I do next. It is some sort of study task, therefore I cant use any libraries.


Solution

  • How about using decorators to print a function's name when it is called? Something like this:

    from functools import wraps
    
    def print_on_entry(fn):
        @wraps(fn)
        def wrapper(*args):
            print "{}({})".format(fn.func_name, ", ".join(str(a) for a in args))
            fn(*args)
        return wrapper
    

    Then you can wrap each of your functions up:

    func1 = print_on_entry(func1)
    func2 = print_on_entry(func2)
    func3 = print_on_entry(func3)
    

    So that:

    >>> func3(1)
    func3(1)
    func2(1)
    func1(1)
    1
    func1(1)
    1
    

    Of course there are a lot of assumptions in the above code -- the arguments can be converted to strings, for example -- but you get the picture.