Python: import a lib with a non-py extenson
Question: I have to import library which is called `functions.sage`. How can I do it? I
tried:

    
    
    __import__('functions.sage')
    

and also this:

    
    
    import imp
    imp.load_source('fun', 'functions.sage')
    

**Edit** :

Actually I want to import [sage](http://en.wikipedia.org/wiki/Sagemath) lib
into sage. And that lib contains sage-specific code. I tired above variants in
sage interpreted. And both gave me 'no functions module' or something like
this.


Answer: This isn't a good idea. (This is right at the borderline between an answer and
a comment, but I wanted to give examples hard to cram into a comment.)

The .sage file either contains Sage-specific syntax and behaviour or it
doesn't. If it doesn't, you can simply rename it to .py, or make a symbolic
link, or whatever. But if it does, then you're going to have to preparse it
anyway before it'll work in Python.

For example, if the "functions.sage" file writes:

    
    
    x = 2/3
    

if you load the file into sage, you get an element of QQ:

    
    
    sage: x
    2/3
    sage: parent(x)
    Rational Field
    

but in Python 2, you'd simply get int(0).

It might use Sage-style ranges:

    
    
    sage: [1,3,..,11]
    [1, 3, 5, 7, 9, 11]
    

or other Sage features:

    
    
    sage: F.<x,y> = GF(2)[]
    sage: F
    Multivariate Polynomial Ring in x, y over Finite Field of size 2
    

and all of these are dealt with by the Sage preparser, not by Python. Behind
the scenes, it's doing this:

    
    
    sage: preparse("F.<x,y> = GF(2)[]") 
    "F = GF(Integer(2))['x, y']; (x, y,) = F._first_ngens(2)"
    

UPDATE: Apparently I didn't make the problem clear enough.

    
    
    sage: import imp 
    sage: !cat functions.sage 
    x = 2/3
    sage: functions = imp.new_module("functions")                         
    sage: execfile("functions.sage", vars(functions))          
    sage: dir(functions)
    ['__builtins__', '__doc__', '__name__', '__package__', 'x']
    sage: functions.x
    0
    sage: type(functions.x)
    <type 'int'>
    

One way or another, you're going to have to pass functions.sage through the
preparser.

