Pythonika
Loading
Pythonika loading.
In[326]:=
Check whether it's alive.
In[329]:=
Out[329]=
Unload.
Usage
Basic examples. (notice that all objects are returned as the corresponding ones in Mathematica )
In[330]:=
Out[330]=
In[331]:=
Py["1+1"]
Out[331]=
In[332]:=
Py["1+2j"]
Out[332]=
Arbitrarily long integers, Python's long's, are properly dealt with.
In[333]:=
Py["2**128"]
Out[333]=
Passing Mathematica's objects to Python
Pythonika provides with Mathematica functions to convert from the most basic types into their equivalent in Python. Beware that symbolic Mathematica expressions may need to be wrapped around N[expr] in order to turn them into a numerical value that can be converted into Python.
The functions take the name of the Python object receiving the data (does not need to exist beforehand) and the value to pass.
Passsing a complex number.
In[334]:=
PyComplex["my_complex", 2+3/2i]
In[335]:=
Py["(my_complex, my_complex.real, my_complex.imag)"]
Out[335]=
Passing a real number.
In[336]:=
PyReal["my_real", N[π/4]]
In[337]:=
Py["(my_real, my_real**2)"]
Out[337]=
Passing a list.
In[338]:=
ToPy["my_list", {1,2,3,4}]
In[339]:=
Py["my_list"]
Out[339]=
In order to make it all simpler, the ToPy function will detect the data type passed and convert it accordingly. Therefore ToPy is the only method needed to pass data to Python.
In[340]:=
ToPy["my_generic", 1/2+2i]
In[341]:=
Py["my_generic"]
Out[341]=
In[342]:=
ToPy[ "my_generic2", N[{2+3i, Sqrt[2]}] ]
In[343]:=
Py["my_generic2"]
Out[343]=
Pythonika can be fed multiline code using Mathematica's "\<" and "\>" in order to preserve the line breaks.
In[344]:=
Py["\<
square_roots = list()
for i in range(10):
square_roots.append(i**.5)
print square_roots[-1]
\>"]
Out[344]=
Retrieve a variable's contents.
In[345]:=
SquareRoots = Py["square_roots"]
Out[345]=
Pythonika can do any iterable object. (This examples work only with Python 2.4 & 2.5, because of the generators)
Sets
In[346]:=
Py["set(x**2 for x in range(10))"]
Out[346]=
Lists
In[347]:=
Py["list(x**2 for x in (2,3,5,7,11,13,17))"]
Out[347]=
Dictionaries
In[348]:=
Py["dict((x, x**2) for x in (2,3,5,7,11,13,17))"]
Out[348]=
This examples work only with Python 2.5, because of the generators
In[349]:=
Py["any(x>5 for x in range(10))"]
Out[349]=
Defining Mathematica functions in Python
This function expects a list as argument.
In[350]:=
This expects a complex, long or integer. (or anything where the power operator is defined)
In[351]:=
Evaluate them
In[352]:=
Out[352]=
Out[353]=
Out[354]=
Define a class with a power operator which raises the value used to initialize an instance to the given exponent and returns the result modulo 7.
In[355]:=
Py["\<
class NN:
def __init__(self, v):
self.v = v
def __pow__(self, exp):
return (self.v**exp)%7
print NN(2)**4
\>"]
Out[355]=
In[356]:=
Py["NN(3)**4"]
Out[356]=
| Created by Mathematica (November 4, 2006) |