Wednesday, December 06, 2006

Jython Quick References

Table 1. Summary of Jython data types

TypeComment Example
NullAn undefined value (like null in the Java language).None
IntegerA normal (int in the Java language) or long (BigInteger in the Java language) integer number.
-1  0  100
-1L 1000000000000000000000000000000000000000000001L

Float A fractional or exponential (like double in the Java language) number.
1.0
-1e6 0.000001e-10 1E11

Complex A pair of floats supporting complex arithmetic.
1j  -10J
2-3j 1e6j

String An immutable sequence of characters. There is no character type (use one character strings instead).
"a string"
'a string'
"""a long (possibly multi-line) string"""
'''another (possibly multi-line) long string'''
r'''^xxx(.*?)\.yyy(.*?)\.zzz(.*?)\.$'''
'x' "y" '\n' "\\"

Range An immutable sequence of integers.
range(10)
range(10,0,-1)
xrange(1,100000,10)

Tuple An immutable sequence of any type (like java.util.Collections.unmodifiableCollection(someList)).
()  (1,)  (1,2,3)
(1, "mixed", 2, "tuple")
((1,2),(3,4))

List A mutable sequence of any type (like java.util.ArrayList).
[]  [1]  [1,2,3]
[1, 'mixed', 2, 'list']
[[1,2],[3,4]]

Map A mutable collection of items (name/value pairs) (like java.util.Map). Names must be immutable and unique; values may be None.
{}
{1:'one',2:'two',3:'three'}
{"one";1, "two":2, "three":3}
{"x":1, "ints":(1,2,3),
"name":{"first":"Barry", last":"Feigenbaum"}}

Boolean A true/false value based on other types. false - 0 or empty:
None
0 0.0
() []


true - non-0, not empty:
1  -1  0.0001
[1] [1,2,3] {"greeting":"Hello!"}

Function Any function. Functions do not need to be members of classes.
lambda x: x > 0

def isPositive(x): return x > 0

def addem(x,y,z):
return x + y + z

Class Any class. Classes are namespaces for class attributes and functions (called methods).
class MyClass:
x = 1
y = 2

class subclass(superClass):
def method1(self): ...

def method2(self, arg1, arg2): ...

Module A source file (and namespace) that contains variable, function and/or class definitions. Any .py file that defines importable variables, functions and/or classes. If it does not define any of these then it is just called a script.


Back to top


Statement types

Jython provides the statement types summarized in Table 2.

Table 2. Summary of Jython statement types

Statement Comment Examples
Expression Any expression. The results are discarded. Often used for their side effects.
(1 * 2) ** 3 / 4

"string"[2:] == "ring"

someFunction(1, 2, 3)

Assignment Assigns an expression to a target.
x = 3
x = f(1,32,3) * 10 + x

list[1:3] = [7, 8, 9 , 10]

Augmented Assignment Updates a target with an expression.
x *= 100

s += "…"

Unpacking Assignment Assigns elements of a sequence to multiple targets; very convenient for access to tuple and list members. Note that the expression 1,2,3 is a short form of (1,2,3).
x,y,z = 1,2,3

Multiple Assignment Assigns the same expression to multiple targets.
z = y = z = 10

Pass No operation.
pass

If
If/Else
If/Elif/Else
Conditional processing.
if x < 0: x = -x

if x == 3:
print "It's three!"

if x == 1: ...
elif x == 2: ...
elif x == 3: ...
else: print "Bad value " + x

While Looping over a condition.
x = 10
while x > 0:
print x
x -= 1

For Iterates over a sequence. Use range to iterate over a numeric sequence.
for i in range(10): print i

for c in "A string":
print c

for i in (10, "Hello", 1e6):
print func(i)

Continue Advances to the next loop (while/for) iteration.
for i in range(10):
if not testOk(i):
continue
:

Break Exits a loop (while/for)
for i in range(10):
if testBad(i):
break
:

Delete Removes a variable or sequence element(s) or class attribute.
del x

del list[3:5]

del x.attr1

Global Declares a reference to a global value; used in functions.
x,y,z = 0,1,2
def f(a,b,c):
global x,y,z
:

Print Prints expression(s) to a stream.
print "Hello World!"
print "Hello","World!"
print "Hello" + ' ' + "World!"

msg = "Name: %(last)s, (first)s"
data = {'last':"Feigenbaum", 'first':"Barry"}
print >>out, msg % data

Assert Asserts a condition is true.
def process(v):
assert v > 0, "Illegal value %i" % v
:

Import Imports all or part of a module.
import sys
from sys import argv
from javax import swing
from java.util import Map

Execute Executes a string/file as a subprogram. There is also a related function, exec, that executes a constructed string and returns its result. This support allows you to dynamically create programs.
globals = {'x':1, 'y':2, 'z':3}
locals = {'list':(1,2,3)}
code = "print x, y, z, list"
exec code in globals, locals

Try/Except Executes code within an exception handler.
try:
x = int(string)
except ValueError, e:
x = 0

Try/Finally Executes code with a cleanup routine.
f = open("test.dat")
try:
lines = f.readlines()
finally:
f.close()

Raise Creates and throws an exception.
def factorial(x):
raise ValueError, "x must be > 0"
:

Define Defines a function; arguments may be optional and/or keywords; Functions are generic which allows for very flexible programming.
def f(x,y=2,z=10): return x+y+z

q = f(1,2) + f(3) + f(4,5,6)
s = f("a","b","c")

Return Returns from a function with an optional value.
return 10

Class Defines a class (a container for attributes and methods) .
class X: pass

class MyClass(SomeClass):
pass



Back to top