This appendix includes two alphabetically sorted, quick-reference tables. Table A.1 shows built-in functions, and Table A.2 shows Jython statements.
Table A.1. Built-In Functions Quick Reference
Function |
Description |
---|---|
|
Returns the absolute value of the number x. Syntax: abs(number) Example: >>> abs(-5.43) 5.43 |
|
Calls an object, the object supplied as the first argument to the apply function. This can be a function, class, or any callable object. If the optional second argument is supplied, it must be a Syntax: apply(object[, args[, kwargs]]) Example: >>> def printKWArgs(**kw): ... print kw ... >>> apply(printKWArgs, (), globals()) {'__name__': '__main__', 'printKWArgs': <function printKWArgs at 2744202>, '__doc__': None} >>> >>> def product(x, y): ... return x * y ... >>> print apply(product, (3, 4)) 12 |
|
Returns Syntax: callable(object) Example: >>> def myFunction(): ... return ... >>> callable(myFunction) 1 >>> callable("a string") 0 |
|
For integers <= 65535, Syntax: chr(integer) Example: >>> chr(119) 'w' >>> chr(88) 'X' >>> chr(50000) u'uC350' |
|
Requires two parameter and returns a value of Syntax: cmp(x, y) Example: >>> cmp(1, 3) -1 >>> cmp(3, 1) 1 >>> cmp(3, 3) 0 |
|
Accepts two objects as parameters, tests if there is a common type that can represent the values of each object. The two values are returned in a Syntax: coerce(x, y) Example: >>> coerce(3.1415, 6) # float and int (3.1415, 6.0) >>>results = coerce("a", 2.3) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: number coercion failed |
|
Compiles a string to a code object. The first parameter is the source string. The second must be a string usually representing the filename. This second argument is used only to make a more descriptive error message so can be any arbitrary string without affecting functionality. The third argument is the mode of compilation, which must be one of three modes:
The returned code object can be executed with the Syntax: compile(source, filename, mode) Example: >>> co = compile("0 and 'This' or 1 and 'that'", "-", "eval") >>> exec(co) >>> eval(co) 'that' >>> co = compile("for x in range(10): print x,", "<console>", "single") >>> exec(co) 0 1 2 3 4 5 6 7 8 9 |
|
Returns a complex number where the real and imaginary parts are created from the two arguments supplied to the function. The complex portion (second argument) is optional, and 0 is used when this argument is not supplied. Syntax: complex(real[, imag]) Example: >>> complex(2) # int to complex (2+0j) >>> complex(3.1, 0.123) # floats to complex (3.1+0.123j) >>> complex("2.1", "0.1234") (2.1000000000000001+0j) |
|
Deletes a specified attribute from an object. Syntax: delattr(object, name) Example: >>> class cache: ... pass # empty class to store arbitrary objects ... >>> c = cache() >>> c.a = 1 >>> c.b = 2 >>> vars(c) {'a': 1, 'b': 2} >>> delattr(c, "a") >>> vars(c) {'b': 2} |
|
If an object is specified, Syntax: dir([object]) Example: >>> a = 1 >>> b = "a string" >>> def aFunction(): ... return ... >>> dir() ['__doc__', '__name__', 'a', 'aFunction', 'b', 'file'] >>> dir(aFunction) ['__dict__', '__doc__', '__name__', 'func_closure', 'func_code', 'func_defaults', 'func_doc', 'func_globals', 'func_name'] |
|
Returns both the integer division and modulus of x divided by y as a Syntax: divmod(x, y) Example: >>> divmod(9,4) (2, 1) >>> divmod(7, 2) (3, 1) |
|
Evaluates a string of code, or a code object created with Syntax: eval(source[, globals[, locals]]) Example: >>> eval("x>3 and x or 0", {'x':4}) 4 >>> eval("x>3 and x or 0", {'x':2}) 0 >>> co = compile("map(lambda x: divmod(x,3), L)", "console", "eval") >>> eval(co, {'L':range(15)}) [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2)] |
|
Executes a file containing Jython code in the specified namespaces. If namespaces are not specified, the current namespaces are used. If only the Syntax: execfile(filename[, globals[, locals]]) Example: >>> # first use an anonymous dictionary for globals >>> execfile("c:\windows\desktop\testfile.py", {}) a b 7 >>> globals() {'__name__': '__main__', '__doc__': None} >>> >>> # Now use current namespaces >>> execfile("c:\windows\desktop\testfile.py") a b 7 >>> globals() {'var2': 'b', 'var1': 'a', '__doc__': None, 'var3': 7, '__name__': '__main_'} |
|
The Syntax: filter(function, sequence) Example: >>> filter(lambda x: x%2, [1,2,3,4,5,6,7,8,9]) [1, 3, 5, 7, 9] >>> filter(None, [1, 0, [], 3-3, {}, 7]) [1, 7] |
|
Returns the first argument, converted to a Syntax: float(x) Example: >>> float(2) # int to float 2.0 >>> float(7L) # long to float 7.0 >>> float(abs(1.1+2.1j)) 2.3706539182259396 >>> float("2.1") # string to float 2.1 |
|
Returns a reference to the specified object attribute. The two arguments required are the object and the attribute name as a string. An optional third argument is the default value to return if the object does not contain the specified attribute. In the case where the object lacks the desired attribute, and the optional third parameter is absent, an Syntax: getattr(object, name[, default]) Example: >>> from time import time >>> class util: ... def __init__(self): ... self.inittime = time() ... >>> u = util() >>> getattr(u, "inittime") 9.8829678293E8 >>> getattr(u, "currenttime", time()) 9.8829681275E8 |
|
Returns a dictionary-like object representing the variables defined in the Syntax: globals() Example: >>> num = 1 >>> string = "a String" >>> globals() {'num': 1, '__name__': '__main__', '__doc__': None, 'string': 'a String'} |
|
Tests whether an object has a specified attribute and returns Syntax: hasattr(object, name) Example: >>> class add: ... def __init__(self): ... pass ... def methodA(self): ... pass ... >>> hasattr(add, "methodA") 1 >>> hasattr(add, "methodB") 0 |
|
Returns an integer that is the specified object’s Syntax: hash(object) Example: >>> a = 1 >>> hash(1) 1 >>> hash(a) 1 >>> c = "dog" >>> hash(c) 1528775661 |
|
Returns the hexadecimal representation of an integer as a string. Syntax: hex(number) Example: >>> hex(16) '0x10' >>> hex(15) '0xf' |
|
Returns an integer representing the unique identification of the specified object. Syntax: id(object) Example: >>> string = "A" >>> id("A") 6262933 |
|
The function Syntax: input([prompt]) Example: >>> input("Enter a Jython expression: ") Enter a Jython expression: 2+3 5 <− the evaluated result of 2++3 |
|
Returns the first argument, converted to an integer ( Syntax: int(x[, base]) Example: >>> int(3.5) # float to int 3 >>> int(5L) # long to int 5 >>> int(abs(2.2+1.72j)) # complex to int 2 >>> int("012", 8) # octal string to int 10 >>> int("0x1A", 16) # hex string to int 26 |
|
This places the specified string in a Syntax: intern(string) Example: >>> string1 = "a" >>> Istring1 = intern(string1) >>> id(string1), id(Istring1) (7347538, 7347538) |
|
Returns Syntax: isinstance(instance, class). Example: >>> import java >>> hm = java.util.HashMap() >>> isinstance(hm, java.util.HashMap) 1 >>> isinstance(hm, java.util.AbstractMap) 1 >>> isinstance(hm, java.util.Vector) 0 |
|
Returns the length of a sequence or mapping type. Syntax: len(object) Example: >>> len("a string") 8 >>> len([1,2,3,4,5]) 5 >>> len(range(0,100,7)) 15 Function Description |
|
Accepts one argument that must be a sequence and returns a list with the same members as those in the argument. Syntax: list(sequence) Example: >>> list("abcdefg") ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> list(("a", "b", "c", "d", "e", "f", "g")) ['a', 'b', 'c', 'd', 'e', 'f', 'g'] |
|
Returns a Syntax: locals() Example: >>> def aFunction(): ... aVariable = "String var" ... print locals() ... >>> aFunction() {'aVariable': 'String var'} |
|
Returns the first argument, converted to a long integer ( Syntax: long(x, base) Example: >>> long(2.7) # float to long 2L >>> long(abs(1.1+2.3j)) # complex to long 2L >>> long("021", 8) # octal string to long 17L >>> long("0xff", 16) # hex string to long 255L |
|
The Syntax: map(function, sequence[, sequence, ...]) Example: >>> map(None, range(6), ["a", "b", "c"]) [(0, 'a'); (1, 'b'); (2, 'c'); (3, None), (4, None), (5, None)] >>> def pad(string): ... return string.rjust(10) ... >>> map(pad, ["a", "b", "c", "d"]) [' a', ' b', ' c', ' d'] |
|
Returns the largest member of specified sequence. The argument must be a sequence. Syntax: max(sequence) Example: >>> max(1,2,3,4,5,6,7,8,9) 9 >>> T = ("strings", "are", "compared", "lexigraphically") >>> max(T) 'strings' |
|
Returns the smallest member of the specified sequence. The argument must be a sequence. Syntax: min(sequence) Example: >>> min(1,2,3,4,5) 1 >>> T = "min returns the smallest char of a string" >>> min(T) ' ' |
|
Returns the octal representation of an integer as a string. Syntax: oct(number) Example: >>> oct(8) '010' >>> oct(7) '07' |
|
Requires a platform-specific file path and name, then opens this designated file and returns the associated file object. The optional mode parameter specifies whether the file is to be opened for reading, writing, appending, or a combination of those. The mode also specifies if the file is binary. Jython requires binary mode be specified to read and write binary data—this is different from CPython. If no mode argument is provided, non-binary, read mode is assumed. Possible values for mode are as follows:
The optional third parameter to the open function designates buffering. the third parameter is currently ignored in Jython. Syntax: open(filename[, mode[, buffering]]) Example: >>> # open file in current directory for reading >>> # plus writing. >>> fo = open("config.cfg", "r+") >>> >>> # Open file for binary reading >>> fo = open("c:sootafBaf.class", "rb") |
|
Returns the integer value of a character. This function is the opposite of Syntax: ord(character) Example: >>> ord('w') 119 >>> ord('X') 88 >>> ord(u'uC350') 50000 |
|
Returns Syntax: pow(x, y[, z]) Example: >>> pow(3, 3) 27 >>> pow(3, 3, 2) 1 |
|
Returns a list of integers built based on the Syntax: range([start,] stop [, step]) Example: >>> range(4) [0, 1, 2, 3] >>> range(3, 6) [3, 4, 5] >>> range(2, 10, 2) [2, 4, 6, 8] |
|
Reads a string from standard input with the trailing newline removed. Syntax: raw_input([prompt]) Example: >>> name = raw_input("Enter your name: ") Enter your name: Bilbo Baggins >>> print name Bilbo Baggins |
|
Reduces a list of values to one value. The two required arguments are a function and a sequence. The third, optional argument is an initial value.The function provided must have two parameters. The reduction happens by applying the function to the first two sequence members, or the initial value and first sequence member if an initial value is supplied. The function is next applied to the results of this first operation and the next sequence member. This cycle continues until the sequence is exhausted and a single value is returned. Syntax: reduce(function, sequence[, initial]) Example: >>> def add(x, y): ... return x + y ... >>> reduce(add, [5,4,3,2,1]) 15 >>> def stripspaces(x, y): ... return x.strip() + y.strip() ... >>> reduce(stripspaces, "A string with spaces") 'Astringwithspaces' |
|
Reloads a specified module. Syntax: reload(module) Example: >>> import math >>> # If the math module changed- reload it. >>> reload(math) <jclass org.python.modules.math at 1401745> |
|
Returns a string that represents the specified object. Syntax: repr(object) Example: >>> repr(123) '123' >>> repr(type) '<java function type at 4737674>' >>> repr("A string") "'A string'" |
|
Returns a floating-point number representing the numeric argument. If the optional argument for the number of significant digits to round to is absent, the number is rounded to 0 decimal places. Otherwise, the number is rounded to the specified number of significant digits from the decimal point. Negative Syntax: round(number[, ndigits]) Example: >>> round(1.23434, 3L) 1.234 >>> round(23.2124) 23.0 >>> round(2) 2.0 |
|
Sets an object’s attribute to a value. The three required arguments are the object, the attribute name as a string, and the value. In Jython, you can set arbitrary attributes on Jython objects, but not on Java objects. This means using Syntax: setattr(object, name, value) Example: >>> class split: ... def __init__(self, token): ... self.token = token ... >>> s = split(":") >>> vars(s) {'token': ':'} >>> setattr(s, 'count', 0) >>> setattr(s, 'token', ",") >>> vars(s) {'token': ',', 'count': 0} >>> >>> # Java objects are different for arbitraryattributes>>> # Note that javax.midi is an optional package- you may need to download it >>> # for this example to work. >>> from javax.sound.midi import VoiceStatus >>> v = VoiceStatus() >>> v.channel 0 >>> setattr(v, "channel", 3) >>> v.channel # "channel" already exists- this works 3 >>> v.channel 3 >>> v.arbitraryVar = 6 # "arbitraryVar doesn't exist Traceback (innermost last): File "<console>", line 1, in ? TypeError: can't set arbitrary attribute in java instance: arbitraryVar |
|
The Syntax: slice([start,] stop[, step]) Example: >>> L = ["s", "o", "r", "c", "q", "a", "p", "j"] >>> sliceobj = slice(7, 0, -2) >>> L[sliceobj] ['j', 'a', 'c', 'o'] |
|
Returns a string representation of an object. Syntax: str(object) Example: >>> str(1) # int to string '1' >>> str(4L) # long to string '4' >>> str(2.2+1.3j) '(2.2+1.3j)' >>> from java.util import Vector >>> str(Vector) 'java.util.Vector' >>> v = Vector() >>> str(v) '[]' >>> v.add(type) # put a function in the vector 1 >>> str(v) '[<java function type at 5229978>]' |
|
Accepts one argument that must be a sequence and returns a Syntax: tuple(sequence) Example: >>> tuple([1,2,3,4,5]) # list to tuple (1, 2, 3, 4, 5) >>> tuple("This is a test") # string to tuple ('T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't') |
|
Returns an object’s type—usually the name of the class in the Syntax: type(object) Example: >>> type("a string") <jclass org.python.core.PyString at 1923370> |
|
This does the same as Syntax: unichr(i) Example: See chr |
|
This creates a new Syntax: unicode(string [, encoding[, errors]]) Example: >>> unicode("Abél", "utf_8", "replace") u'AbuFFFDl' |
|
If an object is specified, Syntax: vars([object]) Example: >>> class aClass: ... def __init__(self): ... attrib1 = "An instance variable" ... attrib2 = "Another instance variable" ... >>> vars(aClass) {'__init__': <function __init__ at 634037>, '__module__': '__main__', '__doc__': None} >>> vars() {'aClass': <class __main__.aClass at 7033304>, '__name__': '__main__', '__doc__': None} |
|
The Syntax: xrange([start,] stop [, step]) Example: See range |
|
Returns a list of Syntax: zip(seq1 [, seq2 [...]]) Example: >>> zip([1,2,3,4,5,6,7], "abcdefg") [(1, 'a'); (2, 'b'); (3, 'c'); (4, 'd'); (5, 'e'); (6, 'f'); (7, 'g')] >>> zip(range(5), range(5,-1,-1)) [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1)] |
Table A.2. Jython Statements Quick Reference
Statement |
Description |
---|---|
|
The Syntax: "assert" expression [, expression] Example: >>>a=21 >>>assert a<10 Traceback (innermost last): File "<console>", line 1, in ? AssertionError: |
|
The Syntax: "break" Example: >>>for x in (1,2,3,4): ... if x==3: ... break ... print x ... 1 2 >>> |
|
Designates the start of a class definition. Syntax: "class" name[(base-class-name(s))]: Example: >>>class test: # no base class ... pass # place holder ... >>>t = test() # Calls class to create an instance |
|
The Syntax: "continue" Example: >>>for x in (1,2,3,4): ... if x==3: ... continue ... print x ... 1 2 4 >>> |
|
Designates the start of a function or method definition. Syntax: "def" name(([parameters]): code-block Example: >>> def caseless_srch_n_replace(string, srch, rplc): ... return string.lower().replace(srch, rplc) ... >>> S = "Some UseLess text" >>> caseless_srch_n_replace(S, "useless", "useful") 'some useful text' |
|
The Syntax: "del" identifier Example: >>>a="foo" >>>print a foo >>>del a >>>print a Traceback (innermost last): File "<console>", line 1, in ? NameError: a |
|
Executes a string, open file object, or a code object supplied as the first expression following the Syntax: "exec" expression ["in" expression ["," expression]] Example: >>>exec("print 'The exec method is used to print this'") The exec method is used to print this |
|
The Syntax: "for" variable "in" expression":" code-block ["else:"] code-block Example: >>> for x in (1, 2, 3): ... print x, "in first code-block" ... else: ... print "In second code-block" ... 1 in first code-block 2 in first code-block 3 in first code-block In second code-block |
|
Explicitly designates that the designated name be referenced from the Syntax: "global" identifier ["," identifier]* Example: >>> var = 10 >>> def test(): ... global var ... print var # try and print the global identifier 'var' ... var = 20 # assign to 'var' in local namespace ... >>> test() 10 |
|
The Syntax: "if" expression: code-block "elif" expression: code-block "else": code-block Example: >>>a, b = 0, 1 >>>if a==b: ... print "variable a equals variable b" ...elif a>b: ... print "variable a is greater than b" ...else: ... print "variable a is less than b" ... variable a is less than b |
|
Imports the specified Jython package, Jython module, Java package, or Java class. This creates a name binding within the namespace import was called. You can optionally change the name imports are bound to with an Syntax: import module-name OR from module-name import names OR import module-name as new-name Example: >>>import sys >>>from java import util >>>import os as myOS >>>from sys import packageManager as pm |
|
The “do nothing” statement. This statement is a placeholder. Syntax: "pass" Example: >>> for x in (1,2,3,4): ... pass ... >>>def doNothing(): ... pass |
|
Evaluates an expression, converts the result to a string if needed and writes the string to Syntax: "print" [expression] OR "print >> " fileLikeObject,, [expression] Example: >>> print "Hello world" Hello world >>> print >> myFile, "Hello world" >>> |
|
The Syntax: "raise" [expression [, expression [, traceback]]] Example: >>> raise ValueError, "No value provided" Traceback (innermost last): File "<console>", line 1, in ? ValueError: no value provided |
|
Terminates execution of the method or function it is within, and returns the value of the evaluated expression it prefixes. If there is no expression, Syntax: "return" [expression] Example: >>> def someFunction(): ... return "This string is the return value" ... >>> print someFunction() This string is the return value |
|
The Syntax: "try:" code-block "except" [expression ["," target]] ":" code-block ["else:" code-block] OR "try:" code-block "finally:" code-block Example: >>> try: ... 1/0 ... except ZeroDivisionError, e: ... print "You cannot divide by zero: ", e ... You cannot divide by zero: integer division or modulo >>> >>> try: ... pass ... finally: ... print "This block always executes" ... This block always executes |
|
The Syntax: "while" expression ":" Example: >>> x = 10 >>> while x>0: ... print x, ... x -= 1 ... 10 9 8 7 6 5 4 3 2 1 >>> |