<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def to_networkx(self, names_only=False):
 """Create a NetworkX graph representing the hierarchy of a Compound. Parameters names_only : bool, optional, default=False Store only the names of the compounds in the graph. When set to False, the default behavior, the nodes are the compounds themselves. Returns ------- G : networkx.DiGraph """

        nx = import_('networkx')

        nodes = list()
        edges = list()
        if names_only:
            nodes.append(self.name)
        else:
            nodes.append(self)
        nodes, edges = self._iterate_children(nodes, edges, names_only=names_only)

        graph = nx.DiGraph()
        graph.add_nodes_from(nodes)
        graph.add_edges_from(edges)
        return graph