First time here? Check out the FAQ!

Ask Your Question
0

[RESOLVED]Use sage objects in python module files

asked 8 years ago

Hyorvenn gravatar image

updated 8 years ago

Hello,

I'm trying to figure out how to use sage functions/classes in a module .py file, from another python file. Here's the thing, I'm developing a small simulator in Python 2 intended to be use with sage for solving diff. equations, etc... So I have different .py files (interface, calcul, etc) in which have been written some code using sage functions.

Let's say I have "y = var('y')" in calcul.py and I run it from sage console ->

sage: load("calcul.py") sage:

All works properly without any failures. But, if I want to import this module in interface.py and then run the file with sage, I get this error ->

sage: load("interface.py") ---> 1 y = var('y')

NameError: name 'var' is not defined

As if it didn't recognize its own functions. Is there any command/function to use in sage to allow loading of imported files without that type of error ?

Thanks in advance for your help.

Preview: (hide)

3 Answers

Sort by » oldest newest most voted
2

answered 8 years ago

eric_g gravatar image

Indeed you have to add

from sage.calculus.var import var

in calcul.py and do the same thing for any Sage name that appears in your module.To know the precise import statement to use, run import_statements in a Sage console:

sage: import_statements(var)
from sage.calculus.var import var
sage: import_statements(SR)
from sage.symbolic.ring import SR
sage: import_statements(pi)
from sage.symbolic.constants import pi
Preview: (hide)
link

Comments

2

And as the documentation of var explains, in a programming/library environment you're better off using y=SR.var('y'). The var function that is used on top-level has some nasty side-effects that are convenient for interactive use, but are bad in library code.

nbruin gravatar imagenbruin ( 8 years ago )

Indeed! Thanks for the correction.

eric_g gravatar imageeric_g ( 8 years ago )

A pointer to the doc? Thanks!

maaaaaaartin gravatar imagemaaaaaaartin ( 8 years ago )
1
0

answered 8 years ago

maaaaaaartin gravatar image

updated 8 years ago

My advice: put import sage.all as sage at the beginning of each python file, and then use for instance sage.var('x') in your scripts.

Preview: (hide)
link
0

answered 8 years ago

Hyorvenn gravatar image

Thanks a lot for your answers !

Preview: (hide)
link

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 8 years ago

Seen: 1,161 times

Last updated: Mar 11 '17