Ask Your Question
0

name 'Graph' is not defined

asked 2024-06-10 14:32:51 +0100

licheng gravatar image

updated 2024-06-10 14:46:00 +0100

Since I have many of my own functions, I plan to organize them into separate modules according to their functionality for easier reuse. I performed the following test by first creating a file zg.py, which contains:

def create_graph():
    G = Graph()
    G.add_edges([(0, 1), (1, 2), (2, 3), (3, 0)])
    return G

When I create a new Sage file and try to call it, the following error appears. Why is this happening? Can't Sage's own functions be used in zg.py?

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[4], line 2
      1 from zg import create_graph
----> 2 create_graph()

File /mnt/d/sage_zhang/new_fun/zg.py:2, in create_graph()
      1 def create_graph():
----> 2     G = Graph()
      3     G.add_edges([(0, 1), (1, 2), (2, 3), (3, 0)])
      4     return G

NameError: name 'Graph' is not defined

image description

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2024-06-10 14:52:09 +0100

eric_g gravatar image

The error occurs because Sage names, like Graph, are automatically imported in an interactive Sage session, but not in a Python file, like zg.py (only pure Python keywords are known in such a file). You have to import them explicitely. In your case, you have to add the following line at the top of the file:

from sage.graphs.graph import Graph

To find which import statement should be added for a given Sage name bla (say), type import_statements("bla") in a Sage session. For instance, in your case:

sage: import_statements("Graph")
from sage.graphs.graph import Graph
edit flag offensive delete link more

Comments

Thank you very much, it may be frustrating. It feels like most Sage functions in zp.py files need to be imported first (even more frightening is that they might belong to different classes.). Is there a more concise way to write a module or to make Sage recognize Sage functions inzp.py

licheng gravatar imagelicheng ( 2024-06-10 15:49:27 +0100 )edit
1

Yes there is a concise way: type load("zp.py") instead of from zg import create_graph: then all Sage names will be automatically recognized.

eric_g gravatar imageeric_g ( 2024-06-10 16:02:30 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2024-06-10 14:32:51 +0100

Seen: 227 times

Last updated: Jun 10