# How to import in an Ipython-Notebook on SMC?

Consider the following scenario (which I tested at SageMathCloud), with an Ipython-Notebook:

%load_ext sage
import trans

def A():
""" Computes the factorial """
n, f = 1, 1
while True:
f = f*n
yield f
n += 1

def binomial_trans(seq):
""" Input : seq sequence generator """
S = []
n = 0
while True:
S.append(seq.next())
yield sum(binomial(n, k) * S[k] for k in (0..n))
n += 1

f = binomial_trans(A())
print [f.next() for _ in range(10)]


This works. Now I would like to outsource the function 'binomial_trans' in a file trans.py and compute

f = trans.binomial_trans(A())
print [f.next() for _ in range(10)]


This does not work. The error message is: AttributeError: 'float' object has no attribute 'n'

What can I do to make the import work together with Sage in an Ipython-Notebook?

Peter

edit retag close merge delete

Sort by » oldest newest most voted

I found the answer here: Question 8303. I renamed the file to trans.sage. Then the first lines in my file are

%load_ext sage
attach('trans.sage')


Interestingly renaming to nemis.sagews and attach('trans.sagews') does not work.

What I am loosing by this method is the possibility to write 'trans.function()' when referring to functions from the 'trans' worksheet.

more

This has nothing to do with SMC, it is a Sage vs Python issue.

The reason is that (0..n) does not exist in Python. Python understands 0..n as follows: 0. is a float corresponding to 0.0, hence 0..n is the method n of the float object 0.0.

Sage understands this the way you want because it has a prepaser that allows such syntaxic sugar, in the same way that 2^2 is preparsed (translated on the fly) into the pythonic 2**2.

Now, when you copy the function binomial_trans() into the trans.py file, this is raw Python without preparsing.

So, you need to transform (0..n) into something equivalent in Python, say range(n+1).

But then, if you try again, you will get a new error NameError: global name 'binomial' is not defined. Indeed, you use the binomial function in a Python file without importing it. To know what to do, you can use the Sage function import_statements() which helps Sage developers a lot (note that Sage source code is made of raw unpreparsed Python files where stuff like that needs to be imported, if you look at the source code you will see a lot of import statements):

sage: import_statements("binomial")
# **Warning**: distinct objects with name 'binomial' in:
#   - sage.functions.other
#   - sage.rings.arith
from sage.rings.arith import binomial


So all what you have to do is to add the line from sage.rings.arith import binomial at the beginning of your file trans.py.

Now it should work.

more