Refactoring graph.py code