Releases of Python (and so releases of Jython) sometimes add new built-in types. In 2.6, a new such buitin is the "bytes" type. In the 2.x series, "bytes" is just a synonym for "str". In 3.x "bytes" is the name used for 8 bit strings while "str" is a unicode string (and so the "unicode" type disappears in 3.x). This will make it a great example for adding a builtin since there is no added functionality to obscure the basics.

First we'll verify that no bytes builtin exists at this time:


[frank jython]$ ./dist/bin/jython
Jython 2.6a0+ (default:9c9c311c201b, Feb 10 2012, 10:29:32)
[OpenJDK 64-Bit Server VM (Sun Microsystems Inc.)] on java1.6.0_23
Type "help", "copyright", "credits" or "license" for more information.
>>> bytes('foo')
Traceback (most recent call last):
File "", line 1, in
NameError: name 'bytes' is not defined


Next we'll look in src/org/python/core/__builtin__.java and add the following:


[frank jython]$ hg diff
diff --git a/src/org/python/core/__builtin__.java b/src/org/python/core/__builtin__.java
--- a/src/org/python/core/__builtin__.java
+++ b/src/org/python/core/__builtin__.java
@@ -305,6 +305,7 @@
dict.__setitem__("Ellipsis", Py.Ellipsis);
dict.__setitem__("True", Py.True);
dict.__setitem__("False", Py.False);
+ dict.__setitem__("bytes", PyString.TYPE);


Since this is just an alias to an existing type, we just needed to point it at the type in builtins. Note that the same entry for "str" is:


dict.__setitem__("str", PyString.TYPE);


So this particular addition to builtin is particularly simple (just one line). Normally we would have needed to implement a new type, which would have been a much bigger change.

And now we'll try it out:


[frank jython]$ ./dist/bin/jython
*sys-package-mgr*: processing modified jar, '/home/frank/hg/jython/jython/dist/jython-dev.jar'
Jython 2.6a0+ (default:9c9c311c201b+, Feb 13 2012, 09:52:10)
[OpenJDK 64-Bit Server VM (Sun Microsystems Inc.)] on java1.6.0_23
Type "help", "copyright", "credits" or "license" for more information.
>>> x = bytes('foo')
>>> x
'foo'
>>> type(x)
<type 'str'>


And there you go!
0

Add a comment

About Me
About Me
Subscribe
Subscribe
Links
Blog Archive
Blog Roll
Blog Roll
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.