Source

dictionary_switches / html / jython.html

Full commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Jython &mdash; Python 3 Patterns & Idioms</title>
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
          URL_ROOT:    '',
          VERSION:     '1.0',
          COLLAPSE_MODINDEX: false,
          FILE_SUFFIX: '.html'
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="shortcut icon" href="_static/favicon.ico"/>
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="top" title="Python 3 Patterns & Idioms" href="index.html" />
    <link rel="next" title="Part II: Idioms" href="Part2.html" />
    <link rel="prev" title="Coroutines &amp; Concurrency" href="CoroutinesAndConcurrency.html" />
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="Part2.html" title="Part II: Idioms"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="CoroutinesAndConcurrency.html" title="Coroutines &amp; Concurrency"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">Python 3 Patterns & Idioms</a> &raquo;</li>
      </ul>
    </div>
    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  
  <div class="section" id="jython">
<h1>Jython<a class="headerlink" href="#jython" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This chapter has not been brought up-to-date with the current
version of Jython.</p>
</div>
<p>This chapter looks at the value of crossing language boundaries. It is often
advantageous to solve a problem using more than one programming language, rather
than being arbitrarily stuck using a single language. As you&#8217;ll see in this
chapter, a problem that is very difficult or tedious to solve in one language
can often be solved quickly and easily in another. If you can combine the use of
languages, you can create your product much more quickly and cheaply.</p>
<p>The most straightforward use of this idea is the <em>Interpreter</em> design pattern,
which adds an interpreted language to your program to allow the end user to
easily customize a solution. In Java, the easiest and most powerful way to do
this is with <em>Jython</em> <a class="footnote-reference" href="#id3" id="id1">[1]</a>, an implementation of the Python language in pure
Java byte codes.</p>
<p><em>Interpreter</em> solves a particular problem - that of creating a scripting
language for the user. But sometimes it&#8217;s just easier and faster to temporarily
step into another language to solve a particular aspect of your problem. You&#8217;re
not creating an interpreter, you&#8217;re just writing some code in another language.
Again, Jython is a good example of this, but CORBA also allows you to cross
language boundaries.</p>
<div class="section" id="interpreter-motivation">
<h2>Interpreter Motivation<a class="headerlink" href="#interpreter-motivation" title="Permalink to this headline">¶</a></h2>
<p>If the application user needs greater run time flexibility, for example to
create scripts describing the desired behavior of the system, you can use the
<em>Interpreter</em> design pattern. Here, you create and embed a language interpreter
into your program.</p>
<p>Remember that each design pattern allows one or more factors to change, so it&#8217;s
important to first be aware of which factor is changing. Sometimes the end users
of your application (rather than the programmers of that application) need
complete flexibility in the way that they configure some aspect of the program.
That is, they need to do some kind of simple programming. The interpreter
pattern provides this flexibility by adding a language interpreter.</p>
<p>The problem is that developing your own language and building an interpreter is
a time-consuming distraction from the process of developing your application.
You must ask whether you want to finish writing your application or create a new
language.  The best solution is to reuse code: embed an interpreter that&#8217;s
already been built and debugged for you. The Python language can be freely
embedded into your for-profit application without signing any license agreement,
paying royalties, or dealing with strings of any kind. There are basically no
restrictions at all when you&#8217;re using Python.</p>
<p>For solving Java problems, we will look at a special version of Python called
Jython. This is generated entirely in Java byte codes, so incorporating it into
your application is quite simple,  and it&#8217;s as portable as Java is. It has an
extremely clean interface with Java: Java can call Python classes, and Python
can call Java classes.</p>
<p>Python is designed with classes from the ground up and is a truly pure object
oriented language (both C++ and Java violate purity in various ways). Python
scales up so that you can create very big programs without losing control of the
code.</p>
<p>To install Jython, go to <a class="reference external" href="http://jython.sourceforge.net">http://jython.sourceforge.net</a>.  The download is a <strong>.class</strong> file, which
will run an installer when you execute it with Java.  You also need to add
<strong>jython.jar</strong> to your Java CLASSPATH.</p>
</div>
<div class="section" id="creating-a-language">
<h2>Creating a Language<a class="headerlink" href="#creating-a-language" title="Permalink to this headline">¶</a></h2>
<p>It turns out to be remarkably simple to use Jython to create an interpreted
language inside your application. Consider the greenhouse controller example
from Chapter 8 of <em>Thinking in Java</em>. This is a situation where you want the end
user - the person managing the greenhouse - to have configuration control over
the system, and so a simple scripting language is the ideal solution.</p>
<p>To create the language, we&#8217;ll simply write a set of Python classes, and the
constructor of each will add itself to a (static) master list. The common data
and behavior will be factored into the base class <strong>Event</strong>. Each <strong>Event</strong>
object will contain an <strong>action</strong> string (for simplicity - in reality, you&#8217;d
have some sort of functionality) and a time when the event is supposed to run.
The constructor initializes these fields, and then adds the new <strong>Event</strong> object
to a static list called <strong>events</strong> (defining it in the class, but outside of any
methods, is what makes it static):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># jython/GreenHouseLanguage.py</span>

<span class="k">class</span> <span class="nc">Event</span><span class="p">:</span>
    <span class="n">events</span> <span class="o">=</span> <span class="p">[]</span> <span class="c"># static</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span> <span class="n">time</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">action</span> <span class="o">=</span> <span class="n">action</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">time</span> <span class="o">=</span> <span class="n">time</span>
        <span class="n">Event</span><span class="o">.</span><span class="n">events</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
    <span class="c"># Used by sort(). This will cause</span>
    <span class="c"># comparisons to be based only on time:</span>
    <span class="k">def</span> <span class="nf">__cmp__</span> <span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">time</span> <span class="o">&lt;</span> <span class="n">other</span><span class="o">.</span><span class="n">time</span><span class="p">:</span> <span class="k">return</span> <span class="o">-</span><span class="mf">1</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">time</span> <span class="o">&gt;</span> <span class="n">other</span><span class="o">.</span><span class="n">time</span><span class="p">:</span> <span class="k">return</span> <span class="mf">1</span>
        <span class="k">return</span> <span class="mf">0</span>
    <span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="s">&quot;</span><span class="si">%.2f</span><span class="s">: </span><span class="si">%s</span><span class="s">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">time</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">action</span><span class="p">))</span>

<span class="k">class</span> <span class="nc">LightOn</span><span class="p">(</span><span class="n">Event</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">time</span><span class="p">):</span>
        <span class="n">Event</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&quot;Light on&quot;</span><span class="p">,</span> <span class="n">time</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">LightOff</span><span class="p">(</span><span class="n">Event</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">time</span><span class="p">):</span>
        <span class="n">Event</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&quot;Light off&quot;</span><span class="p">,</span> <span class="n">time</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">WaterOn</span><span class="p">(</span><span class="n">Event</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">time</span><span class="p">):</span>
        <span class="n">Event</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&quot;Water on&quot;</span><span class="p">,</span> <span class="n">time</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">WaterOff</span><span class="p">(</span><span class="n">Event</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">time</span><span class="p">):</span>
        <span class="n">Event</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&quot;Water off&quot;</span><span class="p">,</span> <span class="n">time</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">ThermostatNight</span><span class="p">(</span><span class="n">Event</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">time</span><span class="p">):</span>
        <span class="n">Event</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="s">&quot;Thermostat night&quot;</span><span class="p">,</span> <span class="n">time</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">ThermostatDay</span><span class="p">(</span><span class="n">Event</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">time</span><span class="p">):</span>
        <span class="n">Event</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&quot;Thermostat day&quot;</span><span class="p">,</span> <span class="n">time</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Bell</span><span class="p">(</span><span class="n">Event</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">time</span><span class="p">):</span>
        <span class="n">Event</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&quot;Ring bell&quot;</span><span class="p">,</span> <span class="n">time</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">run</span><span class="p">():</span>
    <span class="n">Event</span><span class="o">.</span><span class="n">events</span><span class="o">.</span><span class="n">sort</span><span class="p">();</span>
    <span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Event</span><span class="o">.</span><span class="n">events</span><span class="p">:</span>
        <span class="n">e</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>

<span class="c"># To test, this will be run when you say:</span>
<span class="c"># python GreenHouseLanguage.py</span>
<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">ThermostatNight</span><span class="p">(</span><span class="mf">5.00</span><span class="p">)</span>
    <span class="n">LightOff</span><span class="p">(</span><span class="mf">2.00</span><span class="p">)</span>
    <span class="n">WaterOn</span><span class="p">(</span><span class="mf">3.30</span><span class="p">)</span>
    <span class="n">WaterOff</span><span class="p">(</span><span class="mf">4.45</span><span class="p">)</span>
    <span class="n">LightOn</span><span class="p">(</span><span class="mf">1.00</span><span class="p">)</span>
    <span class="n">ThermostatDay</span><span class="p">(</span><span class="mf">6.00</span><span class="p">)</span>
    <span class="n">Bell</span><span class="p">(</span><span class="mf">7.00</span><span class="p">)</span>
    <span class="n">run</span><span class="p">()</span>
</pre></div>
</div>
<p>The constructor of each derived class calls the base-class constructor, which
adds the new object to the list. The <strong>run( )</strong> function sorts the list, which
automatically uses the <strong>__cmp__( )</strong> method that was defined in <strong>Event</strong> to
base comparisons on time only. In this example, it only prints out the list, but
in the real system it would wait for the time of each event to come up and then
run the event.</p>
<p>The <strong>__main__</strong> section performs a simple test on the classes.</p>
<p>The above file is now a module that can be included in another Python program to
define all the classes it contains. But instead of an ordinary Python program,
let&#8217;s use Jython, inside of Java. This turns out to be remarkably simple: you
import some Jython classes, create a <strong>PythonInterpreter</strong> object, and cause the
Python files to be loaded:</p>
<div class="highlight-java"><div class="highlight"><pre><span class="c">// jython/GreenHouseController.java</span>
<span class="kn">package</span> <span class="n">jython</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.util.PythonInterpreter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.core.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">junit.framework.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span>
<span class="nc">GreenHouseController</span> <span class="kd">extends</span> <span class="n">TestCase</span>  <span class="o">{</span>
  <span class="n">PythonInterpreter</span> <span class="n">interp</span> <span class="o">=</span>
    <span class="k">new</span> <span class="nf">PythonInterpreter</span><span class="o">();</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">()</span> <span class="kd">throws</span> <span class="n">PyException</span>  <span class="o">{</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span>
      <span class="s">&quot;Loading GreenHouse Language&quot;</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">execfile</span><span class="o">(</span><span class="s">&quot;GreenHouseLanguage.py&quot;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span>
      <span class="s">&quot;Loading GreenHouse Script&quot;</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">execfile</span><span class="o">(</span><span class="s">&quot;Schedule.ghs&quot;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span>
      <span class="s">&quot;Executing GreenHouse Script&quot;</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;run()&quot;</span><span class="o">);</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span>
  <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">PyException</span>  <span class="o">{</span>
    <span class="n">junit</span><span class="o">.</span><span class="na">textui</span><span class="o">.</span><span class="na">TestRunner</span><span class="o">.</span><span class="na">run</span><span class="o">(</span><span class="n">GreenHouseController</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>The <strong>PythonInterpreter</strong> object is a complete Python interpreter that accepts
commands from the Java program. One of these commands is <strong>execfile( )</strong>, which
tells it to execute all the statements it finds in a particular file. By
executing <strong>GreenHouseLanguage.py</strong>, all the classes from that file are loaded
into our <strong>PythonInterpreter</strong> object, and so it now &#8220;holds&#8221; the greenhouse
controller language. The <strong>Schedule.ghs</strong> file is the one created by the end
user to control the greenhouse. Here&#8217;s an example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># jython/Schedule.ghs</span>
<span class="n">Bell</span><span class="p">(</span><span class="mf">7.00</span><span class="p">)</span>
<span class="n">ThermostatDay</span><span class="p">(</span><span class="mf">6.00</span><span class="p">)</span>
<span class="n">WaterOn</span><span class="p">(</span><span class="mf">3.30</span><span class="p">)</span>
<span class="n">LightOn</span><span class="p">(</span><span class="mf">1.00</span><span class="p">)</span>
<span class="n">ThermostatNight</span><span class="p">(</span><span class="mf">5.00</span><span class="p">)</span>
<span class="n">LightOff</span><span class="p">(</span><span class="mf">2.00</span><span class="p">)</span>
<span class="n">WaterOff</span><span class="p">(</span><span class="mf">4.45</span><span class="p">)</span>
</pre></div>
</div>
<p>This is the goal of the interpreter design pattern: to make the configuration of
your program as simple as possible for the end user. With Jython you can achieve
this with almost no effort at all.</p>
<p>One of the other methods available to the <strong>PythonInterpreter</strong> is <strong>exec( )</strong>,
which allows you to send a command to the interpreter. Here, the <strong>run( )</strong>
function is called using <strong>exec( )</strong>.</p>
</div>
<div class="section" id="controlling-the-interpreter">
<h2>Controlling the Interpreter<a class="headerlink" href="#controlling-the-interpreter" title="Permalink to this headline">¶</a></h2>
<p>The prior example only creates and runs the interpreter using external scripts.
In the rest of this chapter, we shall look at more sophisticated ways to
interact with Jython. The simplest way to exercise more control over the
<strong>PythonInterpreter</strong> object from within Java is to send data to the
interpreter, and pull data back out.</p>
<div class="section" id="putting-data-in">
<h3>Putting Data In<a class="headerlink" href="#putting-data-in" title="Permalink to this headline">¶</a></h3>
<p>To inject data into your Python program, the <strong>PythonInterpreter</strong> class has a
deceptively simple method: <strong>set( )</strong>. However, <strong>set( )</strong> takes many different
data types and performs conversions upon them.  The following example is a
reasonably thorough exercise of the various <strong>set( )</strong> possibilities, along with
comments that should give a fairly complete explanation:</p>
<div class="highlight-java"><div class="highlight"><pre><span class="c">// jython/PythonInterpreterSetting.java</span>
<span class="c">// Passing data from Java to python when using</span>
<span class="c">// the PythonInterpreter object.</span>
<span class="kn">package</span> <span class="n">jython</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.util.PythonInterpreter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.core.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">net.mindview.python.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">junit.framework.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span>
<span class="nc">PythonInterpreterSetting</span> <span class="kd">extends</span> <span class="n">TestCase</span>  <span class="o">{</span>
  <span class="n">PythonInterpreter</span> <span class="n">interp</span> <span class="o">=</span>
    <span class="k">new</span> <span class="nf">PythonInterpreter</span><span class="o">();</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">()</span> <span class="kd">throws</span> <span class="n">PyException</span>  <span class="o">{</span>
    <span class="c">// It automatically converts Strings</span>
    <span class="c">// into native Python strings:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;a&quot;</span><span class="o">,</span> <span class="s">&quot;This is a test&quot;</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(a)&quot;</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(a[5:])&quot;</span><span class="o">);</span> <span class="c">// A slice</span>
    <span class="c">// It also knows what to do with arrays:</span>
    <span class="n">String</span><span class="o">[]</span> <span class="n">s</span> <span class="o">=</span> <span class="o">{</span> <span class="s">&quot;How&quot;</span><span class="o">,</span> <span class="s">&quot;Do&quot;</span><span class="o">,</span> <span class="s">&quot;You&quot;</span><span class="o">,</span> <span class="s">&quot;Do?&quot;</span> <span class="o">};</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;b&quot;</span><span class="o">,</span> <span class="n">s</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;for x in b: print(x[0], x)&quot;</span><span class="o">);</span>
    <span class="c">// set() only takes Objects, so it can&#39;t</span>
    <span class="c">// figure out primitives. Instead,</span>
    <span class="c">// you have to use wrappers:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;c&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">PyInteger</span><span class="o">(</span><span class="mi">1</span><span class="o">));</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;d&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">PyFloat</span><span class="o">(</span><span class="mf">2.2</span><span class="o">));</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(c + d)&quot;</span><span class="o">);</span>
    <span class="c">// You can also use Java&#39;s object wrappers:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;c&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">9</span><span class="o">));</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;d&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">Float</span><span class="o">(</span><span class="mf">3.14</span><span class="o">));</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(c + d)&quot;</span><span class="o">);</span>
    <span class="c">// Define a Python function to print arrays:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span>
      <span class="s">&quot;def prt(x): \n&quot;</span> <span class="o">+</span>
      <span class="s">&quot;  print(x)\n&quot;</span> <span class="o">+</span>
      <span class="s">&quot;  for i in x: \n&quot;</span> <span class="o">+</span>
      <span class="s">&quot;    print(i,)\n&quot;</span> <span class="o">+</span>
      <span class="s">&quot;  print(x.__class__)\n&quot;</span><span class="o">);</span>
    <span class="c">// Arrays are Objects, so it has no trouble</span>
    <span class="c">// figuring out the types contained in arrays:</span>
    <span class="n">Object</span><span class="o">[]</span> <span class="n">types</span> <span class="o">=</span> <span class="o">{</span>
      <span class="k">new</span> <span class="kt">boolean</span><span class="o">[]{</span> <span class="kc">true</span><span class="o">,</span> <span class="kc">false</span><span class="o">,</span> <span class="kc">false</span><span class="o">,</span> <span class="kc">true</span> <span class="o">},</span>
      <span class="k">new</span> <span class="kt">char</span><span class="o">[]{</span> <span class="sc">&#39;a&#39;</span><span class="o">,</span> <span class="sc">&#39;b&#39;</span><span class="o">,</span> <span class="sc">&#39;c&#39;</span><span class="o">,</span> <span class="sc">&#39;d&#39;</span> <span class="o">},</span>
      <span class="k">new</span> <span class="kt">byte</span><span class="o">[]{</span> <span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">,</span> <span class="mi">4</span> <span class="o">},</span>
      <span class="k">new</span> <span class="kt">int</span><span class="o">[]{</span> <span class="mi">10</span><span class="o">,</span> <span class="mi">20</span><span class="o">,</span> <span class="mi">30</span><span class="o">,</span> <span class="mi">40</span> <span class="o">},</span>
      <span class="k">new</span> <span class="kt">long</span><span class="o">[]{</span> <span class="mi">100</span><span class="o">,</span> <span class="mi">200</span><span class="o">,</span> <span class="mi">300</span><span class="o">,</span> <span class="mi">400</span> <span class="o">},</span>
      <span class="k">new</span> <span class="kt">float</span><span class="o">[]{</span> <span class="mf">1.1f</span><span class="o">,</span> <span class="mf">2.2f</span><span class="o">,</span> <span class="mf">3.3f</span><span class="o">,</span> <span class="mf">4.4f</span> <span class="o">},</span>
      <span class="k">new</span> <span class="kt">double</span><span class="o">[]{</span> <span class="mf">1.1</span><span class="o">,</span> <span class="mf">2.2</span><span class="o">,</span> <span class="mf">3.3</span><span class="o">,</span> <span class="mf">4.4</span> <span class="o">},</span>
    <span class="o">};</span>
    <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">types</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
      <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;e&quot;</span><span class="o">,</span> <span class="n">types</span><span class="o">[</span><span class="n">i</span><span class="o">]);</span>
      <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;prt(e)&quot;</span><span class="o">);</span>
    <span class="o">}</span>
    <span class="c">// It uses toString() to print Java objects:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;f&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">Date</span><span class="o">());</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(f)&quot;</span><span class="o">);</span>
    <span class="c">// You can pass it a List</span>
    <span class="c">// and index into it...</span>
    <span class="n">List</span> <span class="n">x</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">();</span>
    <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span>
        <span class="n">x</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="n">i</span> <span class="o">*</span> <span class="mi">10</span><span class="o">));</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;g&quot;</span><span class="o">,</span> <span class="n">x</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(g)&quot;</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(g[1])&quot;</span><span class="o">);</span>
    <span class="c">// ... But it&#39;s not quite smart enough</span>
    <span class="c">// to treat it as a Python array:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(g.__class__)&quot;</span><span class="o">);</span>
    <span class="c">// interp.exec(&quot;print(g[5:])&quot;); // Fails</span>
    <span class="c">// must extract the Java array:</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;ArrayList to array:&quot;</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;h&quot;</span><span class="o">,</span> <span class="n">x</span><span class="o">.</span><span class="na">toArray</span><span class="o">());</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(h.__class__)&quot;</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(h[5:])&quot;</span><span class="o">);</span>
    <span class="c">// Passing in a Map:</span>
    <span class="n">Map</span> <span class="n">m</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">();</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">1</span><span class="o">),</span> <span class="k">new</span> <span class="n">Character</span><span class="o">(</span><span class="sc">&#39;a&#39;</span><span class="o">));</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">3</span><span class="o">),</span> <span class="k">new</span> <span class="n">Character</span><span class="o">(</span><span class="sc">&#39;b&#39;</span><span class="o">));</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">5</span><span class="o">),</span> <span class="k">new</span> <span class="n">Character</span><span class="o">(</span><span class="sc">&#39;c&#39;</span><span class="o">));</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">7</span><span class="o">),</span> <span class="k">new</span> <span class="n">Character</span><span class="o">(</span><span class="sc">&#39;d&#39;</span><span class="o">));</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">11</span><span class="o">),</span> <span class="k">new</span> <span class="n">Character</span><span class="o">(</span><span class="sc">&#39;e&#39;</span><span class="o">));</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;m: &quot;</span> <span class="o">+</span> <span class="n">m</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;m&quot;</span><span class="o">,</span> <span class="n">m</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(m, m.__class__,&quot;</span> <span class="o">+</span>
      <span class="s">&quot;m[1], m[1].__class__)&quot;</span><span class="o">);</span>
    <span class="c">// Not a Python dictionary, so this fails:</span>
    <span class="c">//! interp.exec(&quot;for x in m.keys():&quot; +</span>
    <span class="c">//!   &quot;print(x, m[x])&quot;);</span>
    <span class="c">// To convert a Map to a Python dictionary,</span>
    <span class="c">// use net.mindview.python.PyUtil:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;m&quot;</span><span class="o">,</span> <span class="n">PyUtil</span><span class="o">.</span><span class="na">toPyDictionary</span><span class="o">(</span><span class="n">m</span><span class="o">));</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(m, m.__class__, &quot;</span> <span class="o">+</span>
      <span class="s">&quot;m[1], m[1].__class__)&quot;</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;for x in m.keys():print(x,m[x])&quot;</span><span class="o">);</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span>
  <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">PyException</span>  <span class="o">{</span>
    <span class="n">junit</span><span class="o">.</span><span class="na">textui</span><span class="o">.</span><span class="na">TestRunner</span><span class="o">.</span><span class="na">run</span><span class="o">(</span>
      <span class="n">PythonInterpreterSetting</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>As usual with Java, the distinction between real objects and primitive types
causes trouble. In general, if you pass a regular object to <strong>set( )</strong>, it knows
what to do with it, but if you want to pass in a primitive you must perform a
conversion. One way to do this is to create a &#8220;Py&#8221; type, such as <strong>PyInteger</strong>
or <strong>PyFloat</strong>. but it turns out you can also use Java&#8217;s own object wrappers
like <strong>Integer</strong> and <strong>Float</strong>, which is probably going to be a lot easier to
remember.</p>
<p>Early in the program you&#8217;ll see an <strong>exec( )</strong> containing the Python statement:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="p">[</span><span class="mf">5</span><span class="p">:])</span>
</pre></div>
</div>
<p>The colon inside the indexing statement indicates a Python <em>slice</em>, which
produces a range of elements from the original array. In this case, it produces
an array containing the elements from number 5 until the end of the array. You
could also say &#8216;<strong>a[3:5]</strong>&#8216; to produce elements 3 through 5, or &#8216;<strong>a[:5]</strong>&#8216; to
produce the elements zero through 5. The reason a slice is used in this
statement is to make sure that the Java <strong>String</strong> has really been converted to
a Python string, which can also be treated as an array of characters.</p>
<p>You can see that it&#8217;s possible, using <strong>exec( )</strong>, to create a Python function
(although it&#8217;s a bit awkward). The <strong>prt( )</strong> function prints the whole array,
and then (to make sure it&#8217;s a real Python array), iterates through each element
of the array and prints it. Finally, it prints the class of the array, so we can
see what conversion has taken place (Python not only has run-time type
information, it also has the equivalent of Java reflection). The <strong>prt( )</strong>
function is used to print arrays that come from each of the Java primitive
types.</p>
<p>Although a Java <strong>ArrayList</strong> does pass into the interpreter using <strong>set( )</strong>,
and you can index into it as if it were an array, trying to create a slice
fails. To completely convert it into an array, one approach is to simply extract
a Java array using <strong>toArray( )</strong>, and pass that in. The <strong>set( )</strong> method
converts it to a <strong>PyArray</strong> - one of the classes provided with Jython - which
can be treated as a Python array (you can also explicitly create a <strong>PyArray</strong>,
but this seems unnecessary).</p>
<p>Finally, a <strong>Map</strong> is created and passed directly into the interpreter. While it
is possible to do simple things like index into the resulting object, it&#8217;s not a
real Python dictionary so you can&#8217;t (for example) call the <strong>keys( )</strong> method.
There is no straightforward way to convert a Java <strong>Map</strong> into a Python
dictionary, and so I wrote a utility called <strong>toPyDictionary( )</strong> and made it a
<strong>static</strong> method of <strong>net.mindview.python.PyUtil</strong>. This also includes
utilities to extract a Python array into a Java <strong>List</strong>, and a Python
dictionary into a Java <strong>Map</strong>:</p>
<div class="highlight-java"><div class="highlight"><pre><span class="c">// jython/PyUtil.java</span>
<span class="c">// PythonInterpreter utilities</span>
<span class="kn">package</span> <span class="n">net</span><span class="o">.</span><span class="na">mindview</span><span class="o">.</span><span class="na">python</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.util.PythonInterpreter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.core.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">PyUtil</span> <span class="o">{</span>
  <span class="c">/** Extract a Python tuple or array into a Java</span>
<span class="c">  List (which can be converted into other kinds</span>
<span class="c">  of lists and sets inside Java).</span>
<span class="c">  @param interp The Python interpreter object</span>
<span class="c">  @param pyName The id of the python list object</span>
<span class="c">  */</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="n">List</span>
  <span class="nf">toList</span><span class="o">(</span><span class="n">PythonInterpreter</span> <span class="n">interp</span><span class="o">,</span> <span class="n">String</span> <span class="n">pyName</span><span class="o">){</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">ArrayList</span><span class="o">(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span>
      <span class="o">(</span><span class="n">Object</span><span class="o">[])</span><span class="n">interp</span><span class="o">.</span><span class="na">get</span><span class="o">(</span>
        <span class="n">pyName</span><span class="o">,</span> <span class="n">Object</span><span class="o">[].</span><span class="na">class</span><span class="o">)));</span>
  <span class="o">}</span>
  <span class="c">/** Extract a Python dictionary into a Java Map</span>
<span class="c">  @param interp The Python interpreter object</span>
<span class="c">  @param pyName The id of the python dictionary</span>
<span class="c">  */</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="n">Map</span>
  <span class="nf">toMap</span><span class="o">(</span><span class="n">PythonInterpreter</span> <span class="n">interp</span><span class="o">,</span> <span class="n">String</span> <span class="n">pyName</span><span class="o">){</span>
    <span class="n">PyList</span> <span class="n">pa</span> <span class="o">=</span> <span class="o">((</span><span class="n">PyDictionary</span><span class="o">)</span><span class="n">interp</span><span class="o">.</span><span class="na">get</span><span class="o">(</span>
      <span class="n">pyName</span><span class="o">)).</span><span class="na">items</span><span class="o">();</span>
    <span class="n">Map</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">();</span>
    <span class="k">while</span><span class="o">(</span><span class="n">pa</span><span class="o">.</span><span class="na">__len__</span><span class="o">()</span> <span class="o">!=</span> <span class="mi">0</span><span class="o">)</span> <span class="o">{</span>
      <span class="n">PyTuple</span> <span class="n">po</span> <span class="o">=</span> <span class="o">(</span><span class="n">PyTuple</span><span class="o">)</span><span class="n">pa</span><span class="o">.</span><span class="na">pop</span><span class="o">();</span>
      <span class="n">Object</span> <span class="n">first</span> <span class="o">=</span> <span class="n">po</span><span class="o">.</span><span class="na">__finditem__</span><span class="o">(</span><span class="mi">0</span><span class="o">)</span>
        <span class="o">.</span><span class="na">__tojava__</span><span class="o">(</span><span class="n">Object</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
      <span class="n">Object</span> <span class="n">second</span> <span class="o">=</span> <span class="n">po</span><span class="o">.</span><span class="na">__finditem__</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span>
        <span class="o">.</span><span class="na">__tojava__</span><span class="o">(</span><span class="n">Object</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
      <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">first</span><span class="o">,</span> <span class="n">second</span><span class="o">);</span>
    <span class="o">}</span>
    <span class="k">return</span> <span class="n">map</span><span class="o">;</span>
  <span class="o">}</span>
  <span class="c">/** Turn a Java Map into a PyDictionary,</span>
<span class="c">  suitable for placing into a PythonInterpreter</span>
<span class="c">  @param map The Java Map object</span>
<span class="c">  */</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="n">PyDictionary</span>
  <span class="nf">toPyDictionary</span><span class="o">(</span><span class="n">Map</span> <span class="n">map</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Map</span> <span class="n">m</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">();</span>
    <span class="n">Iterator</span> <span class="n">it</span> <span class="o">=</span> <span class="n">map</span><span class="o">.</span><span class="na">entrySet</span><span class="o">().</span><span class="na">iterator</span><span class="o">();</span>
    <span class="k">while</span><span class="o">(</span><span class="n">it</span><span class="o">.</span><span class="na">hasNext</span><span class="o">())</span> <span class="o">{</span>
      <span class="n">Map</span><span class="o">.</span><span class="na">Entry</span> <span class="n">e</span> <span class="o">=</span> <span class="o">(</span><span class="n">Map</span><span class="o">.</span><span class="na">Entry</span><span class="o">)</span><span class="n">it</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
      <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">Py</span><span class="o">.</span><span class="na">java2py</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">getKey</span><span class="o">()),</span>
        <span class="n">Py</span><span class="o">.</span><span class="na">java2py</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">getValue</span><span class="o">()));</span>
    <span class="o">}</span>
    <span class="c">// PyDictionary constructor wants a Hashtable:</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">PyDictionary</span><span class="o">(</span><span class="k">new</span> <span class="n">Hashtable</span><span class="o">(</span><span class="n">m</span><span class="o">));</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>Here is the (black-box) unit testing code:</p>
<div class="highlight-java"><div class="highlight"><pre><span class="c">// jython/Test.java</span>
<span class="kn">package</span> <span class="n">net</span><span class="o">.</span><span class="na">mindview</span><span class="o">.</span><span class="na">python</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.util.PythonInterpreter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">junit.framework.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Test</span> <span class="kd">extends</span> <span class="n">TestCase</span>  <span class="o">{</span>
  <span class="n">PythonInterpreter</span> <span class="n">pi</span> <span class="o">=</span>
    <span class="k">new</span> <span class="nf">PythonInterpreter</span><span class="o">();</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test1</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">pi</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;tup=(&#39;fee&#39;,&#39;fi&#39;,&#39;fo&#39;,&#39;fum&#39;,&#39;fi&#39;)&quot;</span><span class="o">);</span>
    <span class="n">List</span> <span class="n">lst</span> <span class="o">=</span> <span class="n">PyUtil</span><span class="o">.</span><span class="na">toList</span><span class="o">(</span><span class="n">pi</span><span class="o">,</span> <span class="s">&quot;tup&quot;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">lst</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="k">new</span> <span class="n">HashSet</span><span class="o">(</span><span class="n">lst</span><span class="o">));</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test2</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">pi</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;ints=[1,3,5,7,9,11,13,17,19]&quot;</span><span class="o">);</span>
    <span class="n">List</span> <span class="n">lst</span> <span class="o">=</span> <span class="n">PyUtil</span><span class="o">.</span><span class="na">toList</span><span class="o">(</span><span class="n">pi</span><span class="o">,</span> <span class="s">&quot;ints&quot;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">lst</span><span class="o">);</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test3</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">pi</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;dict = { 1 : &#39;a&#39;, 3 : &#39;b&#39;, &quot;</span> <span class="o">+</span>
      <span class="s">&quot;5 : &#39;c&#39;, 9 : &#39;d&#39;, 11 : &#39;e&#39;}&quot;</span><span class="o">);</span>
    <span class="n">Map</span> <span class="n">mp</span> <span class="o">=</span> <span class="n">PyUtil</span><span class="o">.</span><span class="na">toMap</span><span class="o">(</span><span class="n">pi</span><span class="o">,</span> <span class="s">&quot;dict&quot;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">mp</span><span class="o">);</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test4</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">Map</span> <span class="n">m</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">();</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&quot;twas&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">11</span><span class="o">));</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&quot;brillig&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">27</span><span class="o">));</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&quot;and&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">47</span><span class="o">));</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&quot;the&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">42</span><span class="o">));</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&quot;slithy&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">33</span><span class="o">));</span>
    <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&quot;toves&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">55</span><span class="o">));</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">m</span><span class="o">);</span>
    <span class="n">pi</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;m&quot;</span><span class="o">,</span> <span class="n">PyUtil</span><span class="o">.</span><span class="na">toPyDictionary</span><span class="o">(</span><span class="n">m</span><span class="o">));</span>
    <span class="n">pi</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(m)&quot;</span><span class="o">);</span>
    <span class="n">pi</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(m[&#39;slithy&#39;])&quot;</span><span class="o">);</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span> <span class="n">args</span><span class="o">[])</span> <span class="o">{</span>
    <span class="n">junit</span><span class="o">.</span><span class="na">textui</span><span class="o">.</span><span class="na">TestRunner</span><span class="o">.</span><span class="na">run</span><span class="o">(</span><span class="n">Test</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>We&#8217;ll see the use of the extraction tools in the next section.</p>
</div>
<div class="section" id="getting-data-out">
<h3>Getting Data Out<a class="headerlink" href="#getting-data-out" title="Permalink to this headline">¶</a></h3>
<p>There are a number of different ways to extract data from the
<strong>PythonInterpreter</strong>. If you simply call the <strong>get( )</strong> method, passing it the
object identifier as a string, it returns a <strong>PyObject</strong> (part of the
<strong>org.python.core</strong> support classes). It&#8217;s possible to &#8220;cast&#8221; it using the
<strong>__tojava__( )</strong> method, but there are better alternatives:</p>
<ol class="arabic simple">
<li>The convenience methods in the <strong>Py</strong> class, such as <strong>py2int( )</strong>, take a
<strong>PyObject</strong> and convert it to a number of different types.</li>
<li>An overloaded version of <strong>get( )</strong> takes the desired Java <strong>Class</strong> object
as a second argument, and produces an object that has that run-time type (so you
still need to perform a cast on the result in your Java code).</li>
</ol>
<p>Using the second approach, getting an array from the <strong>PythonInterpreter</strong> is
quite easy. This is especially useful because Python is exceptionally good at
manipulating strings and files, and so you will commonly want to extract the
results as an array of strings. For example, you can do a wildcard expansion of
file names using Python&#8217;s <strong>glob( )</strong>, as shown further down in the following
code:</p>
<div class="highlight-java"><div class="highlight"><pre><span class="c">// jython/PythonInterpreterGetting.java</span>
<span class="c">// Getting data from the PythonInterpreter object.</span>
<span class="kn">package</span> <span class="n">jython</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.util.PythonInterpreter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.core.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">net.mindview.python.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">junit.framework.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span>
<span class="nc">PythonInterpreterGetting</span> <span class="kd">extends</span> <span class="n">TestCase</span> <span class="o">{</span>
  <span class="n">PythonInterpreter</span> <span class="n">interp</span> <span class="o">=</span>
    <span class="k">new</span> <span class="nf">PythonInterpreter</span><span class="o">();</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">()</span> <span class="kd">throws</span> <span class="n">PyException</span>  <span class="o">{</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;a = 100&quot;</span><span class="o">);</span>
    <span class="c">// If you just use the ordinary get(),</span>
    <span class="c">// it returns a PyObject:</span>
    <span class="n">PyObject</span> <span class="n">a</span> <span class="o">=</span> <span class="n">interp</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&quot;a&quot;</span><span class="o">);</span>
    <span class="c">// There&#39;s not much you can do with a generic</span>
    <span class="c">// PyObject, but you can print it out:</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;a = &quot;</span> <span class="o">+</span> <span class="n">a</span><span class="o">);</span>
    <span class="c">// If you know the type it&#39;s supposed to be,</span>
    <span class="c">// you can &quot;cast&quot; it using __tojava__() to</span>
    <span class="c">// that Java type and manipulate it in Java.</span>
    <span class="c">// To use &#39;a&#39; as an int, you must use</span>
    <span class="c">// the Integer wrapper class:</span>
    <span class="kt">int</span> <span class="n">ai</span><span class="o">=</span> <span class="o">((</span><span class="n">Integer</span><span class="o">)</span><span class="n">a</span><span class="o">.</span><span class="na">__tojava__</span><span class="o">(</span><span class="n">Integer</span><span class="o">.</span><span class="na">class</span><span class="o">))</span>
      <span class="o">.</span><span class="na">intValue</span><span class="o">();</span>
    <span class="c">// There are also convenience functions:</span>
    <span class="n">ai</span> <span class="o">=</span> <span class="n">Py</span><span class="o">.</span><span class="na">py2int</span><span class="o">(</span><span class="n">a</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;ai + 47 = &quot;</span> <span class="o">+</span> <span class="o">(</span><span class="n">ai</span> <span class="o">+</span> <span class="mi">47</span><span class="o">));</span>
    <span class="c">// You can convert it to different types:</span>
    <span class="kt">float</span> <span class="n">af</span> <span class="o">=</span> <span class="n">Py</span><span class="o">.</span><span class="na">py2float</span><span class="o">(</span><span class="n">a</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;af + 47 = &quot;</span> <span class="o">+</span> <span class="o">(</span><span class="n">af</span> <span class="o">+</span> <span class="mi">47</span><span class="o">));</span>
    <span class="c">// If you try to cast it to an inappropriate</span>
    <span class="c">// type you&#39;ll get a runtime exception:</span>
    <span class="c">//! String as = (String)a.__tojava__(</span>
    <span class="c">//!   String.class);</span>

    <span class="c">// If you know the type, a more useful method</span>
    <span class="c">// is the overloaded get() that takes the</span>
    <span class="c">// desired class as the 2nd argument:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;x = 1 + 2&quot;</span><span class="o">);</span>
    <span class="kt">int</span> <span class="n">x</span> <span class="o">=</span> <span class="o">((</span><span class="n">Integer</span><span class="o">)</span><span class="n">interp</span>
      <span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&quot;x&quot;</span><span class="o">,</span> <span class="n">Integer</span><span class="o">.</span><span class="na">class</span><span class="o">)).</span><span class="na">intValue</span><span class="o">();</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;x = &quot;</span> <span class="o">+</span> <span class="n">x</span><span class="o">);</span>

    <span class="c">// Since Python is so good at manipulating</span>
    <span class="c">// strings and files, you will often need to</span>
    <span class="c">// extract an array of Strings. Here, a file</span>
    <span class="c">// is read as a Python array:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;lines = &quot;</span> <span class="o">+</span>
      <span class="s">&quot;open(&#39;PythonInterpreterGetting.java&#39;)&quot;</span> <span class="o">+</span>
      <span class="s">&quot;.readlines()&quot;</span><span class="o">);</span>
    <span class="c">// Pull it in as a Java array of String:</span>
    <span class="n">String</span><span class="o">[]</span> <span class="n">lines</span> <span class="o">=</span> <span class="o">(</span><span class="n">String</span><span class="o">[])</span>
      <span class="n">interp</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&quot;lines&quot;</span><span class="o">,</span> <span class="n">String</span><span class="o">[].</span><span class="na">class</span><span class="o">);</span>
    <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span>
      <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">print</span><span class="o">(</span><span class="n">lines</span><span class="o">[</span><span class="n">i</span><span class="o">]);</span>

    <span class="c">// As an example of useful string tools,</span>
    <span class="c">// global expansion of ambiguous file names</span>
    <span class="c">// using glob is very useful, but it&#39;s not</span>
    <span class="c">// part of the standard Jython package, so</span>
    <span class="c">// you&#39;ll have to make sure that your</span>
    <span class="c">// Python path is set to include these, or</span>
    <span class="c">// that you deliver the necessary Python</span>
    <span class="c">// files with your application.</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;from glob import glob&quot;</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;files = glob(&#39;*.java&#39;)&quot;</span><span class="o">);</span>
    <span class="n">String</span><span class="o">[]</span> <span class="n">files</span> <span class="o">=</span> <span class="o">(</span><span class="n">String</span><span class="o">[])</span>
      <span class="n">interp</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&quot;files&quot;</span><span class="o">,</span> <span class="n">String</span><span class="o">[].</span><span class="na">class</span><span class="o">);</span>
    <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">files</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span>
      <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">files</span><span class="o">[</span><span class="n">i</span><span class="o">]);</span>

    <span class="c">// You can extract tuples and arrays into</span>
    <span class="c">// Java Lists with net.mindview.PyUtil:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span>
      <span class="s">&quot;tup = (&#39;fee&#39;, &#39;fi&#39;, &#39;fo&#39;, &#39;fum&#39;, &#39;fi&#39;)&quot;</span><span class="o">);</span>
    <span class="n">List</span> <span class="n">tup</span> <span class="o">=</span> <span class="n">PyUtil</span><span class="o">.</span><span class="na">toList</span><span class="o">(</span><span class="n">interp</span><span class="o">,</span> <span class="s">&quot;tup&quot;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">tup</span><span class="o">);</span>
    <span class="c">// It really is a list of String objects:</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">tup</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="mi">0</span><span class="o">).</span><span class="na">getClass</span><span class="o">());</span>
    <span class="c">// You can easily convert it to a Set:</span>
    <span class="n">Set</span> <span class="n">tups</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashSet</span><span class="o">(</span><span class="n">tup</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">tups</span><span class="o">);</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;ints=[1,3,5,7,9,11,13,17,19]&quot;</span><span class="o">);</span>
    <span class="n">List</span> <span class="n">ints</span> <span class="o">=</span> <span class="n">PyUtil</span><span class="o">.</span><span class="na">toList</span><span class="o">(</span><span class="n">interp</span><span class="o">,</span> <span class="s">&quot;ints&quot;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ints</span><span class="o">);</span>
    <span class="c">// It really is a List of Integer objects:</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">((</span><span class="n">ints</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="mi">1</span><span class="o">)).</span><span class="na">getClass</span><span class="o">());</span>

    <span class="c">// If you have a Python dictionary, it can</span>
    <span class="c">// be extracted into a Java Map, again with</span>
    <span class="c">// net.mindview.PyUtil:</span>
    <span class="n">interp</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;dict = { 1 : &#39;a&#39;, 3 : &#39;b&#39;,&quot;</span> <span class="o">+</span>
      <span class="s">&quot;5 : &#39;c&#39;, 9 : &#39;d&#39;, 11 : &#39;e&#39; }&quot;</span><span class="o">);</span>
    <span class="n">Map</span> <span class="n">map</span> <span class="o">=</span> <span class="n">PyUtil</span><span class="o">.</span><span class="na">toMap</span><span class="o">(</span><span class="n">interp</span><span class="o">,</span> <span class="s">&quot;dict&quot;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;map: &quot;</span> <span class="o">+</span> <span class="n">map</span><span class="o">);</span>
    <span class="c">// It really is Java objects, not PyObjects:</span>
    <span class="n">Iterator</span> <span class="n">it</span> <span class="o">=</span> <span class="n">map</span><span class="o">.</span><span class="na">entrySet</span><span class="o">().</span><span class="na">iterator</span><span class="o">();</span>
    <span class="n">Map</span><span class="o">.</span><span class="na">Entry</span> <span class="n">e</span> <span class="o">=</span> <span class="o">(</span><span class="n">Map</span><span class="o">.</span><span class="na">Entry</span><span class="o">)</span><span class="n">it</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">getKey</span><span class="o">().</span><span class="na">getClass</span><span class="o">());</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">getValue</span><span class="o">().</span><span class="na">getClass</span><span class="o">());</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span>
  <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">PyException</span>  <span class="o">{</span>
    <span class="n">junit</span><span class="o">.</span><span class="na">textui</span><span class="o">.</span><span class="na">TestRunner</span><span class="o">.</span><span class="na">run</span><span class="o">(</span>
      <span class="n">PythonInterpreterGetting</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>The last two examples show the extraction of Python tuples and lists into Java
<strong>List**s, and Python dictionaries into Java **Map**s. Both of these cases
require more processing than is provided in the standard Jython library, so I
have again created utilities in **net.mindview.pyton.PyUtil</strong>: <strong>toList( )</strong> to
produce a <strong>List</strong> from a Python sequence, and <strong>toMap( )</strong> to produce a <strong>Map</strong>
from a Python dictionary. The <strong>PyUtil</strong> methods make it easier to take
important data structures back and forth between Java and Python.</p>
</div>
<div class="section" id="multiple-interpreters">
<h3>Multiple Interpreters<a class="headerlink" href="#multiple-interpreters" title="Permalink to this headline">¶</a></h3>
<p>It&#8217;s also worth noting that you can have multiple <strong>PythonInterpreter</strong> objects
in a program, and each one has its own name space:</p>
<div class="highlight-java"><div class="highlight"><pre><span class="c">// jython/MultipleJythons.java</span>
<span class="c">// You can run multiple interpreters, each</span>
<span class="c">// with its own name space.</span>
<span class="kn">package</span> <span class="n">jython</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.util.PythonInterpreter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.core.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">junit.framework.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MultipleJythons</span> <span class="kd">extends</span> <span class="n">TestCase</span>  <span class="o">{</span>
  <span class="n">PythonInterpreter</span>
    <span class="n">interp1</span> <span class="o">=</span>  <span class="k">new</span> <span class="n">PythonInterpreter</span><span class="o">(),</span>
    <span class="n">interp2</span> <span class="o">=</span>  <span class="k">new</span> <span class="n">PythonInterpreter</span><span class="o">();</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">()</span> <span class="kd">throws</span> <span class="n">PyException</span> <span class="o">{</span>
    <span class="n">interp1</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;a&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">PyInteger</span><span class="o">(</span><span class="mi">42</span><span class="o">));</span>
    <span class="n">interp2</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="s">&quot;a&quot;</span><span class="o">,</span> <span class="k">new</span> <span class="n">PyInteger</span><span class="o">(</span><span class="mi">47</span><span class="o">));</span>
    <span class="n">interp1</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(a)&quot;</span><span class="o">);</span>
    <span class="n">interp2</span><span class="o">.</span><span class="na">exec</span><span class="o">(</span><span class="s">&quot;print(a)&quot;</span><span class="o">);</span>
    <span class="n">PyObject</span> <span class="n">x1</span> <span class="o">=</span> <span class="n">interp1</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&quot;a&quot;</span><span class="o">);</span>
    <span class="n">PyObject</span> <span class="n">x2</span> <span class="o">=</span> <span class="n">interp2</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&quot;a&quot;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;a from interp1: &quot;</span> <span class="o">+</span> <span class="n">x1</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;a from interp2: &quot;</span> <span class="o">+</span> <span class="n">x2</span><span class="o">);</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span>
  <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">PyException</span>  <span class="o">{</span>
    <span class="n">junit</span><span class="o">.</span><span class="na">textui</span><span class="o">.</span><span class="na">TestRunner</span><span class="o">.</span><span class="na">run</span><span class="o">(</span><span class="n">MultipleJythons</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>When you run the program you&#8217;ll see that the value of <strong>a</strong> is distinct within
each <strong>PythonInterpreter</strong>.</p>
</div>
</div>
<div class="section" id="controlling-java-from-jython">
<h2>Controlling Java from Jython<a class="headerlink" href="#controlling-java-from-jython" title="Permalink to this headline">¶</a></h2>
<p>Since you have the Java language at your disposal, and you can set and retrieve
values in the interpreter, there&#8217;s a tremendous amount that you can accomplish
with the above approach (controlling Python from Java).  But one of the amazing
things about Jython is that it makes Java classes almost transparently available
from within Jython. Basically, a Java class looks like a Python class. This is
true for standard Java library classes as well as classes that you create
yourself, as you can see here:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># jython/JavaClassInPython.py</span>
<span class="c"># run with: jython.bat JavaClassInPython.py</span>
<span class="c"># Using Java classes within Jython</span>
<span class="kn">from</span> <span class="nn">java.util</span> <span class="kn">import</span> <span class="n">Date</span><span class="p">,</span> <span class="n">HashSet</span><span class="p">,</span> <span class="n">HashMap</span>
<span class="kn">from</span> <span class="nn">jython.javaclass</span> <span class="kn">import</span> <span class="n">JavaClass</span>
<span class="kn">from</span> <span class="nn">math</span> <span class="kn">import</span> <span class="n">sin</span>

<span class="n">d</span> <span class="o">=</span> <span class="n">Date</span><span class="p">()</span> <span class="c"># Creating a Java Date object</span>
<span class="k">print</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="c"># Calls toString()</span>

<span class="c"># A &quot;generator&quot; to easily create data:</span>
<span class="k">class</span> <span class="nc">ValGen</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">maxVal</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">val</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="n">maxVal</span><span class="p">)</span>
    <span class="c"># Called during &#39;for&#39; iteration:</span>
    <span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span>
        <span class="c"># Returns a tuple of two elements:</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">val</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="n">sin</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">val</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>

<span class="c"># Java standard containers:</span>
<span class="nb">map</span> <span class="o">=</span> <span class="n">HashMap</span><span class="p">()</span>
<span class="n">set</span> <span class="o">=</span> <span class="n">HashSet</span><span class="p">()</span>

<span class="k">for</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">ValGen</span><span class="p">(</span><span class="mf">10</span><span class="p">):</span>
    <span class="nb">map</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
    <span class="n">set</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
    <span class="n">set</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>

<span class="k">print</span><span class="p">(</span><span class="nb">map</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">set</span><span class="p">)</span>

<span class="c"># Iterating through a set:</span>
<span class="k">for</span> <span class="n">z</span> <span class="ow">in</span> <span class="n">set</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">z</span><span class="p">,</span> <span class="n">z</span><span class="o">.</span><span class="n">__class__</span><span class="p">)</span>

<span class="k">print</span><span class="p">(</span><span class="nb">map</span><span class="p">[</span><span class="mf">3</span><span class="p">])</span> <span class="c"># Uses Python dictionary indexing</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">map</span><span class="o">.</span><span class="n">keySet</span><span class="p">():</span> <span class="c"># keySet() is a Map method</span>
    <span class="k">print</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="nb">map</span><span class="p">[</span><span class="n">x</span><span class="p">])</span>

<span class="c"># Using a Java class that you create yourself is</span>
<span class="c"># just as easy:</span>
<span class="n">jc</span> <span class="o">=</span> <span class="n">JavaClass</span><span class="p">()</span>
<span class="n">jc2</span> <span class="o">=</span> <span class="n">JavaClass</span><span class="p">(</span><span class="s">&quot;Created within Jython&quot;</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">jc2</span><span class="o">.</span><span class="n">getVal</span><span class="p">())</span>
<span class="n">jc</span><span class="o">.</span><span class="n">setVal</span><span class="p">(</span><span class="s">&quot;Using a Java class is trivial&quot;</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">jc</span><span class="o">.</span><span class="n">getVal</span><span class="p">())</span>
<span class="k">print</span><span class="p">(</span><span class="n">jc</span><span class="o">.</span><span class="n">getChars</span><span class="p">())</span>
<span class="n">jc</span><span class="o">.</span><span class="n">val</span> <span class="o">=</span> <span class="s">&quot;Using bean properties&quot;</span>
<span class="k">print</span><span class="p">(</span><span class="n">jc</span><span class="o">.</span><span class="n">val</span><span class="p">)</span>
</pre></div>
</div>
<p>The &#8220;<strong>=M</strong>&#8221; comment is recognized by the makefile generator tool (that I
created for this book) as a replacement makefile command. This will be used
instead of the commands that the extraction tool would normally place in the
makefile.</p>
<p>Note that the <strong>import</strong> statements map to the Java package structure exactly as
you would expect. In the first example, a <strong>Date( )</strong> object is created as if it
were a native Python class, and printing this object just calls <strong>toString( )</strong>.</p>
<p><strong>ValGen</strong> implements the concept of a &#8220;generator&#8221; which is used a great deal in
the C++ STL (<em>Standard Template Library</em>, part of the Standard C++ Library). A
generator is an object that produces a new object every time its &#8220;generation
method&#8221; is called, and it is quite convenient for filling containers. Here, I
wanted to use it in a <strong>for</strong> iteration, and so I needed the generation method
to be the one that is called by the iteration process. This is a special method
called <strong>__getitem__( )</strong>, which is actually the overloaded operator for
indexing, &#8216;<strong>[ ]</strong>&#8216;. A <strong>for</strong> loop calls this method every time it wants to
move the iteration forward, and when the elements run out, <strong>__getitem__( )</strong>
throws an out-of-bounds exception and that signals the end of the <strong>for</strong> loop
(in other languages, you would never use an exception for ordinary control flow,
but in Python it seems to work quite well). This exception happens automatically
when <strong>self.val[i]</strong> runs out of elements, so the <strong>__getitem__( )</strong> code turns
out to be simple. The only complexity is that <strong>__getitem__( )</strong> appears to
return <em>two</em> objects instead of just one. What Python does is automatically
package multiple return values into a tuple, so you still only end up returning
a single object (in C++ or Java you would have to create your own data structure
to accomplish this). In addition, in the <strong>for</strong> loop where <strong>ValGen</strong> is used,
Python automatically &#8220;unpacks&#8221; the tuple so that you can have multiple iterators
in the <strong>for</strong>. These are the kinds of syntax simplifications that make Python
so endearing.</p>
<p>The <strong>map</strong> and <strong>set</strong> objects are instances of Java&#8217;s <strong>HashMap</strong> and
<strong>HashSet</strong>, again created as if those classes were just native Python
components. In the <strong>for</strong> loop, the <strong>put( )</strong> and <strong>add( )</strong> methods work just
like they do in Java. Also, indexing into a Java <strong>Map</strong> uses the same notation
as for dictionaries, but note that to iterate through the keys in a <strong>Map</strong> you
must use the <strong>Map</strong> method <strong>keySet( )</strong> rather than the Python dictionary
method <strong>keys( )</strong>.</p>
<p>The final part of the example shows the use of a Java class that I created from
scratch, to demonstrate how trivial it is. Notice also that Jython intuitively
understands JavaBeans properties, since you can either use the <strong>getVal( )</strong> and
<strong>setVal( )</strong> methods, or assign to and read from the equivalent <strong>val</strong>
property. Also, <strong>getChars( )</strong> returns a <strong>Character[]</strong> in Java, and this
becomes an array in Python.</p>
<p>The easiest way to use Java classes that you create for use inside a Python
program is to put them inside a package. Although Jython can also import
unpackaged java classes (<strong>import JavaClass</strong>), all such unpackaged java classes
will be treated as if they were defined in different packages so they can only
see each other&#8217;s public methods.</p>
<p>Java packages translate into Python modules, and Python must import a module in
order to be able to use the Java class. Here is the Java code for <strong>JavaClass</strong>:</p>
<div class="highlight-java"><div class="highlight"><pre><span class="c">// jython/javaclass/JavaClass.java</span>
<span class="kn">package</span> <span class="n">jython</span><span class="o">.</span><span class="na">javaclass</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">junit.framework.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">JavaClass</span> <span class="o">{</span>
  <span class="kd">private</span> <span class="n">String</span> <span class="n">s</span> <span class="o">=</span> <span class="s">&quot;&quot;</span><span class="o">;</span>
  <span class="kd">public</span> <span class="nf">JavaClass</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;JavaClass()&quot;</span><span class="o">);</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="nf">JavaClass</span><span class="o">(</span><span class="n">String</span> <span class="n">a</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">a</span><span class="o">;</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;JavaClass(String)&quot;</span><span class="o">);</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="n">String</span> <span class="nf">getVal</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;getVal()&quot;</span><span class="o">);</span>
    <span class="k">return</span> <span class="n">s</span><span class="o">;</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">setVal</span><span class="o">(</span><span class="n">String</span> <span class="n">a</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;setVal()&quot;</span><span class="o">);</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">a</span><span class="o">;</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="n">Character</span><span class="o">[]</span> <span class="nf">getChars</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;getChars()&quot;</span><span class="o">);</span>
    <span class="n">Character</span><span class="o">[]</span> <span class="n">r</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Character</span><span class="o">[</span><span class="n">s</span><span class="o">.</span><span class="na">length</span><span class="o">()];</span>
    <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">s</span><span class="o">.</span><span class="na">length</span><span class="o">();</span> <span class="n">i</span><span class="o">++)</span>
      <span class="n">r</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Character</span><span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">charAt</span><span class="o">(</span><span class="n">i</span><span class="o">));</span>
    <span class="k">return</span> <span class="n">r</span><span class="o">;</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="kd">class</span> <span class="nc">Test</span> <span class="kd">extends</span> <span class="n">TestCase</span>  <span class="o">{</span>
    <span class="n">JavaClass</span>
      <span class="n">x1</span> <span class="o">=</span> <span class="k">new</span> <span class="n">JavaClass</span><span class="o">(),</span>
      <span class="n">x2</span> <span class="o">=</span> <span class="k">new</span> <span class="n">JavaClass</span><span class="o">(</span><span class="s">&quot;UnitTest&quot;</span><span class="o">);</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test1</span><span class="o">()</span> <span class="o">{</span>
      <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">x2</span><span class="o">.</span><span class="na">getVal</span><span class="o">());</span>
      <span class="n">x1</span><span class="o">.</span><span class="na">setVal</span><span class="o">(</span><span class="s">&quot;SpamEggsSausageAndSpam&quot;</span><span class="o">);</span>
      <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span>
        <span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">x1</span><span class="o">.</span><span class="na">getChars</span><span class="o">()));</span>
    <span class="o">}</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">junit</span><span class="o">.</span><span class="na">textui</span><span class="o">.</span><span class="na">TestRunner</span><span class="o">.</span><span class="na">run</span><span class="o">(</span><span class="n">Test</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>You can see that this is just an ordinary Java class, without any awareness that
it will be used in a Jython program. For this reason, one of the important uses
of Jython is in testing Java code <a class="footnote-reference" href="#id4" id="id2">[2]</a>. Because Python is such a powerful,
flexible, dynamic language it is an ideal tool for automated test frameworks,
without making any changes to the Java code that&#8217;s being tested.</p>
<div class="section" id="inner-classes">
<h3>Inner Classes<a class="headerlink" href="#inner-classes" title="Permalink to this headline">¶</a></h3>
<p>Inner classes becomes attributes on the class object. Instances of <strong>static</strong>
inner classes can be created with the usual call:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">com</span><span class="o">.</span><span class="n">foo</span><span class="o">.</span><span class="n">JavaClass</span><span class="o">.</span><span class="n">StaticInnerClass</span><span class="p">()</span>
</pre></div>
</div>
<p>Non-<strong>static</strong> inner classes must have an outer class instance supplied
explicitly as the first argument:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">com</span><span class="o">.</span><span class="n">foo</span><span class="o">.</span><span class="n">JavaClass</span><span class="o">.</span><span class="n">InnerClass</span><span class="p">(</span><span class="n">com</span><span class="o">.</span><span class="n">foo</span><span class="o">.</span><span class="n">JavaClass</span><span class="p">())</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="using-java-libraries">
<h2>Using Java libraries<a class="headerlink" href="#using-java-libraries" title="Permalink to this headline">¶</a></h2>
<p>Jython wraps the Java libraries so that any of them can be used directly or via
inheritance. In addition, Python shorthand simplifies coding.</p>
<p>As an example, consider the <strong>HTMLButton.java</strong> example from Chapter 9 of
<em>Thinking in Java</em> (you presumably have already downloaded and installed the
source code for that book from <a class="reference external" href="http://www.MindviewInc.com">www.MindviewInc.com</a>, since a number of examples in this book use
libraries from that book). Here is its conversion to Jython:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># jython/PythonSwing.py</span>
<span class="c"># The HTMLButton.java example from</span>
<span class="c"># &quot;Thinking in Java, 2nd edition,&quot; Chapter 13,</span>
<span class="c"># converted into Jython.</span>
<span class="c"># Don&#39;t run this as part of the automatic make:</span>
<span class="c">#=M @echo skipping PythonSwing.py</span>
<span class="kn">from</span> <span class="nn">javax.swing</span> <span class="kn">import</span> <span class="n">JFrame</span><span class="p">,</span> <span class="n">JButton</span><span class="p">,</span> <span class="n">JLabel</span>
<span class="kn">from</span> <span class="nn">java.awt</span> <span class="kn">import</span> <span class="n">FlowLayout</span>

<span class="n">frame</span> <span class="o">=</span> <span class="n">JFrame</span><span class="p">(</span><span class="s">&quot;HTMLButton&quot;</span><span class="p">,</span> <span class="n">visible</span><span class="o">=</span><span class="mf">1</span><span class="p">,</span>
  <span class="n">defaultCloseOperation</span><span class="o">=</span><span class="n">JFrame</span><span class="o">.</span><span class="n">EXIT_ON_CLOSE</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">kapow</span><span class="p">(</span><span class="n">e</span><span class="p">):</span>
    <span class="n">frame</span><span class="o">.</span><span class="n">contentPane</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">JLabel</span><span class="p">(</span><span class="s">&quot;&lt;html&gt;&quot;</span><span class="o">+</span>
      <span class="s">&quot;&lt;i&gt;&lt;font size=+4&gt;Kapow!&quot;</span><span class="p">))</span>
    <span class="c"># Force a re-layout to</span>
    <span class="c"># include the new label:</span>
    <span class="n">frame</span><span class="o">.</span><span class="n">validate</span><span class="p">()</span>

<span class="n">button</span> <span class="o">=</span> <span class="n">JButton</span><span class="p">(</span><span class="s">&quot;&lt;html&gt;&lt;b&gt;&lt;font size=+2&gt;&quot;</span> <span class="o">+</span>
  <span class="s">&quot;&lt;center&gt;Hello!&lt;br&gt;&lt;i&gt;Press me now!&quot;</span><span class="p">,</span>
  <span class="n">actionPerformed</span><span class="o">=</span><span class="n">kapow</span><span class="p">)</span>
<span class="n">frame</span><span class="o">.</span><span class="n">contentPane</span><span class="o">.</span><span class="n">layout</span> <span class="o">=</span> <span class="n">FlowLayout</span><span class="p">()</span>
<span class="n">frame</span><span class="o">.</span><span class="n">contentPane</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">button</span><span class="p">)</span>
<span class="n">frame</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>
<span class="n">frame</span><span class="o">.</span><span class="n">size</span><span class="o">=</span><span class="mf">200</span><span class="p">,</span> <span class="mf">500</span>
</pre></div>
</div>
<p>If you compare the Java version of the program to the above Jython
implementation, you&#8217;ll see that Jython is shorter and generally easier to
understand. For example, in the Java version to set up the frame you had to make
several calls: the constructor for <strong>JFrame( )</strong>, the <strong>setVisible( )</strong> method
and the <strong>setDefaultCloseOperation( )</strong> method, whereas in the above code all
three of these operations are performed with a single constructor call.</p>
<p>Also notice that the <strong>JButton</strong> is configured with an <strong>actionListener( )</strong>
method inside the constructor, with the assignment to <strong>kapow</strong>. In addition,
Jython&#8217;s JavaBean awareness means that a call to any method with a name that
begins with &#8220;<strong>set</strong>&#8221; can be replaced with an assignment, as you can see above.</p>
<p>The only method that did not come over from Java is the <strong>pack( )</strong> method,
which seems to be essential in order to force the layout to happen properly.
It&#8217;s also important that the call to <strong>pack( )</strong> appear <em>before</em> the <strong>size</strong>
setting.</p>
<div class="section" id="inheriting-from-java-library-classes">
<h3>Inheriting from Java library Classes<a class="headerlink" href="#inheriting-from-java-library-classes" title="Permalink to this headline">¶</a></h3>
<p>You can easily inherit from standard Java library classes in Jython. Here&#8217;s the
<strong>Dialogs.java</strong> example from Chapter 13 of <em>Thinking in Java</em>, converted into
Jython:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># jython/PythonDialogs.py</span>
<span class="c"># Dialogs.java from &quot;Thinking in Java, 2nd</span>
<span class="c"># edition,&quot; Chapter 13, converted into Jython.</span>
<span class="c"># Don&#39;t run this as part of the automatic make:</span>
<span class="c">#=M @echo skipping PythonDialogs.py</span>
<span class="kn">from</span> <span class="nn">java.awt</span> <span class="kn">import</span> <span class="n">FlowLayout</span>
<span class="kn">from</span> <span class="nn">javax.swing</span> <span class="kn">import</span> <span class="n">JFrame</span><span class="p">,</span> <span class="n">JDialog</span><span class="p">,</span> <span class="n">JLabel</span>
<span class="kn">from</span> <span class="nn">javax.swing</span> <span class="kn">import</span> <span class="n">JButton</span>

<span class="k">class</span> <span class="nc">MyDialog</span><span class="p">(</span><span class="n">JDialog</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">parent</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="n">JDialog</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span>
          <span class="n">title</span><span class="o">=</span><span class="s">&quot;My dialog&quot;</span><span class="p">,</span> <span class="n">modal</span><span class="o">=</span><span class="mf">1</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">contentPane</span><span class="o">.</span><span class="n">layout</span> <span class="o">=</span> <span class="n">FlowLayout</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">contentPane</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">JLabel</span><span class="p">(</span><span class="s">&quot;A dialog!&quot;</span><span class="p">))</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">contentPane</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">JButton</span><span class="p">(</span><span class="s">&quot;OK&quot;</span><span class="p">,</span>
          <span class="n">actionPerformed</span> <span class="o">=</span>
            <span class="k">lambda</span> <span class="n">e</span><span class="p">,</span> <span class="n">t</span><span class="o">=</span><span class="bp">self</span><span class="p">:</span> <span class="n">t</span><span class="o">.</span><span class="n">dispose</span><span class="p">()))</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>

<span class="n">frame</span> <span class="o">=</span> <span class="n">JFrame</span><span class="p">(</span><span class="s">&quot;Dialogs&quot;</span><span class="p">,</span> <span class="n">visible</span><span class="o">=</span><span class="mf">1</span><span class="p">,</span>
  <span class="n">defaultCloseOperation</span><span class="o">=</span><span class="n">JFrame</span><span class="o">.</span><span class="n">EXIT_ON_CLOSE</span><span class="p">)</span>
<span class="n">dlg</span> <span class="o">=</span> <span class="n">MyDialog</span><span class="p">()</span>
<span class="n">frame</span><span class="o">.</span><span class="n">contentPane</span><span class="o">.</span><span class="n">add</span><span class="p">(</span>
  <span class="n">JButton</span><span class="p">(</span><span class="s">&quot;Press here to get a Dialog Box&quot;</span><span class="p">,</span>
    <span class="n">actionPerformed</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">e</span><span class="p">:</span> <span class="n">dlg</span><span class="o">.</span><span class="n">show</span><span class="p">()))</span>
<span class="n">frame</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>
</pre></div>
</div>
<p><strong>MyDialog</strong> is inherited from <strong>JDialog</strong>, and you can see named arguments
being used in the call to the base-class constructor.</p>
<p>In the creation of the &#8220;OK&#8221; <strong>JButton</strong>, note that the <strong>actionPerformed</strong>
method is set right inside the constructor, and that the function is created
using the Python <strong>lambda</strong> keyword. This creates a nameless function with the
arguments appearing before the colon and the expression that generates the
returned value after the colon. As you should know, the Java prototype for the
<strong>actionPerformed( )</strong> method only contains a single argument, but the lambda
expression indicates two. However, the second argument is provided with a
default value, so the function <em>can</em> be called with only one argument. The
reason for the second argument is seen in the default value, because this is a
way to pass <strong>self</strong> into the lambda expression, so that it can be used to
dispose of the dialog.</p>
<p>Compare this code with the version that&#8217;s published in <em>Thinking in Java</em>.
You&#8217;ll find that Python language features allow a much more succinct and direct
implementation.</p>
</div>
</div>
<div class="section" id="creating-java-classes-with-jython">
<h2>Creating Java classes with Jython<a class="headerlink" href="#creating-java-classes-with-jython" title="Permalink to this headline">¶</a></h2>
<p>Although it does not directly relate to the original problem of this chapter
(creating an interpreter), Jython has the additional ability to create Java
classes directly from your Jython code. This can produce very useful results, as
you are then able to treat the results as if they are native Java classes,
albeit with Python power under the hood.</p>
<p>To produce Java classes from Python code, Jython comes with a compiler called
<strong>jythonc</strong>.</p>
<p>The process of creating Python classes that will produce Java classes is a bit
more complex than when calling Java classes from Python, because the methods in
Java classes are strongly typed, while Python functions and methods are weakly
typed. Thus, you must somehow tell <strong>jythonc</strong> that a Python method is intended
to have a particular set of argument types and that its return value is a
particular type. You accomplish this with the &#8220;&#64;sig&#8221; string, which is placed
right after the beginning of the Python method definition (this is the standard
location for the Python documentation string). For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">returnArray</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="s">&quot;@sig public java.lang.String[] returnArray()&quot;</span>
</pre></div>
</div>
<p>The Python definition doesn&#8217;t specify any return type, but the &#64;sig string gives
the full type information about what is being passed and returned. The
<strong>jythonc</strong> compiler uses this information to generate the correct Java code.</p>
<p>There&#8217;s one other set of rules you must follow in order to get a successful
compilation: you must inherit from a Java class or interface in your Python
class (you do not need to specify the <strong>&#64;sig</strong> signature for methods defined in
the superclass/interface). If you do not do this, you won&#8217;t get your desired
methods - unfortunately, <strong>jythonc</strong> gives you no warnings or errors in this
case, but you won&#8217;t get what you want. If you don&#8217;t see what&#8217;s missing, it can
be very frustrating.</p>
<p>In addition, you must import the appropriate java class and give the correct
package specification.  In the example below, <strong>java</strong> is imported so you must
inherit from <strong>java.lang.Object</strong>, but you could also say <strong>from java.lang
import Object</strong> and then you&#8217;d just inherit from <strong>Object</strong> without the package
specification. Unfortunately, you don&#8217;t get any warnings or errors if you get
this wrong, so you must be patient and keep trying.</p>
<p>Here is an example of a Python class created to produce a Java class. This also
introduces the &#8216;<strong>=T</strong>&#8216; directive for the makefile builder tool, which specifies
a different target than the one that is normally used by the tool. In this case,
the Python file is used to build a Java <strong>.class</strong> file, so the class file is
the desired makefile target. To accomplish this, the default makefile command is
replaced using the &#8216;<strong>=M</strong>&#8216; directive (notice how you can break across lines
using &#8216;<strong>\</strong>&#8216;):</p>
<div class="highlight-python"><pre># jython/PythonToJavaClass.py
#=T python\java\test\PythonToJavaClass.class
#=M jythonc.bat --package python.java.test \
#=M PythonToJavaClass.py
# A Python class created to produce a Java class
from jarray import array
import java

class PythonToJavaClass(java.lang.Object):
    # The '@sig' signature string is used to create
    # the proper signature in the resulting
    # Java code:
    def __init__(self):
        "@sig public PythonToJavaClass()"
        print("Constructor for PythonToJavaClass")

    def simple(self):
        "@sig public void simple()"
        print("simple()")

    # Returning values to Java:
    def returnString(self):
        "@sig public java.lang.String returnString()"
        return "howdy"

    # You must construct arrays to return along
    # with the type of the array:
    def returnArray(self):
        "@sig public java.lang.String[] returnArray()"
        test = [ "fee", "fi", "fo", "fum" ]
        return array(test, java.lang.String)

    def ints(self):
        "@sig public java.lang.Integer[] ints()"
        test = [ 1, 3, 5, 7, 11, 13, 17, 19, 23 ]
        return array(test, java.lang.Integer)

    def doubles(self):
        "@sig public java.lang.Double[] doubles()"
        test = [ 1, 3, 5, 7, 11, 13, 17, 19, 23 ]
        return array(test, java.lang.Double)

    # Passing arguments in from Java:
    def argIn1(self, a):
        "@sig public void argIn1(java.lang.String a)"
        print("a: %s" % a)
        print("a.__class__", a.__class__)

    def argIn2(self, a):
        "@sig public void argIn1(java.lang.Integer a)"
        print("a + 100: %d" % (a + 100))
        print("a.__class__", a.__class__)

    def argIn3(self, a):
        "@sig public void argIn3(java.util.List a)"
        print("received List:", a, a.__class__)
        print("element type:", a[0].__class__)
        print("a[3] + a[5]:", a[5] + a[7])
        #! print("a[2:5]:", a[2:5]) # Doesn't work

    def argIn4(self, a):
        "@sig public void \
           argIn4(org.python.core.PyArray a)"
        print("received type:", a.__class__)
        print("a: ", a)
        print("element type:", a[0].__class__)
        print("a[3] + a[5]:", a[5] + a[7])
        print("a[2:5]:", a[2:5] # A real Python array)

    # A map must be passed in as a PyDictionary:
    def argIn5(self, m):
        "@sig public void \
           argIn5(org.python.core.PyDictionary m)"
        print("received Map: ", m, m.__class__)
        print("m['3']:", m['3'])
        for x in m.keys():
            print(x, m[x])</pre>
</div>
<p>First note that <strong>PythonToJavaClass</strong> is inherited from <strong>java.lang.Object</strong>; if
you don&#8217;t do this you will quietly get a Java class without the right
signatures. You are not required to inherit from <strong>Object</strong>; any other Java
class will do.</p>
<p>This class is designed to demonstrate different  arguments and return values, to
provide you with enough examples that you&#8217;ll be able to easily create your own
signature strings. The first three of these are fairly self-explanatory, but
note the full qualification of the Java name in the signature string.</p>
<p>In <strong>returnArray( )</strong>, a Python array must be returned as a Java array. To do
this, the Jython <strong>array( )</strong> function (from the <strong>jarray</strong> module) must be
used, along with the type of the class for the resulting array. Any time you
need to return an array to Java, you must use <strong>array( )</strong>, as seen in the
methods <strong>ints( )</strong> and <strong>doubles( )</strong>.</p>
<p>The last methods show how to pass arguments in from Java. Basic types happen
automatically as long as you specify them in the <strong>&#64;sig</strong> string, but you must
use objects and you cannot pass in primitives (that is, primitives must be
ensconced in wrapper objects, such as <strong>Integer</strong>).</p>
<p>In <strong>argIn3( )</strong>, you can see that a Java <strong>List</strong> is transparently converted to
something that behaves just like a Python array, but is not a true array because
you cannot take a slice from it. If you want a true Python array, then you must
create and pass a <strong>PyArray</strong> as in <strong>argIn4( )</strong>, where the slice is
successful. Similarly, a Java <strong>Map</strong> must come in as a <strong>PyDictionary</strong> in
order to be treated as a Python dictionary.</p>
<p>Here is the Java program to exercise the Java classes produced by the above
Python code. This also introduces the &#8216;<strong>=D</strong>&#8216; directive for the makefile
builder tool, which specifies a dependency in addition to those detected by the
tool. Here, you can&#8217;t compile <strong>TestPythonToJavaClass.java</strong> until
<strong>PythonToJavaClass.class</strong> is available:</p>
<div class="highlight-java"><div class="highlight"><pre><span class="c">// jython/TestPythonToJavaClass.java</span>
<span class="c">//+D python\java\test\PythonToJavaClass.class</span>
<span class="kn">package</span> <span class="n">jython</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.lang.reflect.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.python.core.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">junit.framework.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">net.mindview.python.*</span><span class="o">;</span>
<span class="c">// The package with the Python-generated classes:</span>
<span class="kn">import</span> <span class="nn">python.java.test.*</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span>
<span class="nc">TestPythonToJavaClass</span> <span class="kd">extends</span> <span class="n">TestCase</span>  <span class="o">{</span>
  <span class="n">PythonToJavaClass</span> <span class="n">p2j</span> <span class="o">=</span> <span class="k">new</span> <span class="n">PythonToJavaClass</span><span class="o">();</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">testDumpClassInfo</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span>
      <span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span>
        <span class="n">p2j</span><span class="o">.</span><span class="na">getClass</span><span class="o">().</span><span class="na">getConstructors</span><span class="o">()));</span>
    <span class="n">Method</span><span class="o">[]</span> <span class="n">methods</span> <span class="o">=</span>
      <span class="n">p2j</span><span class="o">.</span><span class="na">getClass</span><span class="o">().</span><span class="na">getMethods</span><span class="o">();</span>
    <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">methods</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
      <span class="n">String</span> <span class="n">nm</span> <span class="o">=</span> <span class="n">methods</span><span class="o">[</span><span class="n">i</span><span class="o">].</span><span class="na">toString</span><span class="o">();</span>
      <span class="k">if</span><span class="o">(</span><span class="n">nm</span><span class="o">.</span><span class="na">indexOf</span><span class="o">(</span><span class="s">&quot;PythonToJavaClass&quot;</span><span class="o">)</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span><span class="o">)</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">nm</span><span class="o">);</span>
    <span class="o">}</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test1</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">p2j</span><span class="o">.</span><span class="na">simple</span><span class="o">();</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">p2j</span><span class="o">.</span><span class="na">returnString</span><span class="o">());</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span>
      <span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">p2j</span><span class="o">.</span><span class="na">returnArray</span><span class="o">()));</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span>
      <span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">p2j</span><span class="o">.</span><span class="na">ints</span><span class="o">());</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span>
      <span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">p2j</span><span class="o">.</span><span class="na">doubles</span><span class="o">()));</span>
    <span class="n">p2j</span><span class="o">.</span><span class="na">argIn1</span><span class="o">(</span><span class="s">&quot;Testing argIn1()&quot;</span><span class="o">);</span>
    <span class="n">p2j</span><span class="o">.</span><span class="na">argIn2</span><span class="o">(</span><span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="mi">47</span><span class="o">));</span>
    <span class="n">ArrayList</span> <span class="n">a</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">();</span>
    <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span>
      <span class="n">a</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="n">Integer</span><span class="o">(</span><span class="n">i</span><span class="o">));</span>
    <span class="n">p2j</span><span class="o">.</span><span class="na">argIn3</span><span class="o">(</span><span class="n">a</span><span class="o">);</span>
    <span class="n">p2j</span><span class="o">.</span><span class="na">argIn4</span><span class="o">(</span>
      <span class="k">new</span> <span class="nf">PyArray</span><span class="o">(</span><span class="n">Integer</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="n">a</span><span class="o">.</span><span class="na">toArray</span><span class="o">()));</span>
    <span class="n">Map</span> <span class="n">m</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">();</span>
    <span class="k">for</span><span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span>
      <span class="n">m</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&quot;&quot;</span> <span class="o">+</span> <span class="n">i</span><span class="o">,</span> <span class="k">new</span> <span class="n">Float</span><span class="o">(</span><span class="n">i</span><span class="o">));</span>
    <span class="n">p2j</span><span class="o">.</span><span class="na">argIn5</span><span class="o">(</span><span class="n">PyUtil</span><span class="o">.</span><span class="na">toPyDictionary</span><span class="o">(</span><span class="n">m</span><span class="o">));</span>
  <span class="o">}</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">junit</span><span class="o">.</span><span class="na">textui</span><span class="o">.</span><span class="na">TestRunner</span><span class="o">.</span><span class="na">run</span><span class="o">(</span>
      <span class="n">TestPythonToJavaClass</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>For Python support, you&#8217;ll usually only need to import the classes in
<strong>org.python.core</strong>. Everything else in the above example is fairly
straightforward, as <strong>PythonToJavaClass</strong> appears, from the Java side, to be
just another Java class. <strong>dumpClassInfo( )</strong> uses reflection to verify that the
method signatures specified in <strong>PythonToJavaClass.py</strong> have come through
properly.</p>
<div class="section" id="building-java-classes-from-python">
<h3>Building Java Classes from Python<a class="headerlink" href="#building-java-classes-from-python" title="Permalink to this headline">¶</a></h3>
<p>Part of the trick of creating Java classes from Python code is the &#64;sig
information in the method documentation strings. But there&#8217;s a second problem
which stems from the fact that Python has no &#8220;package&#8221; keyword - the Python
equivalent of packages (modules) are implicitly created based on the file name.
However, to bring the resulting class files into the Java program, <strong>jythonc</strong>
must be given information about how to create the Java package for the Python
code. This is done on the <strong>jythonc</strong> command line using the <strong>&#8211;package</strong> flag,
followed by the package name you wish to produce (including the separation dots,
just as you would give the package name using the <strong>package</strong> keyword in a Java
program). This will put the resulting <strong>.class</strong> files in the appropriate
subdirectory off of the current directory. Then you only need to import the
package in your Java program, as shown above (you&#8217;ll need &#8216;<strong>.</strong>&#8216; in your
CLASSPATH in order to run it from the code directory).</p>
<p>Here are the <strong>make</strong> dependency rules that I used to build the above example
(the backslashes at the ends of the lines are understood by <strong>make</strong> to be line
continuations). These rules are encoded into the above Java and Python files
using the comment syntax that&#8217;s understood by my makefile builder tool:</p>
<div class="highlight-python"><pre>TestPythonToJavaClass.class: \\
        TestPythonToJavaClass.java \\
        python\java\test\PythonToJavaClass.class
    javac TestPythonToJavaClass.java

python\java\test\PythonToJavaClass.class: \\
        PythonToJavaClass.py
    jythonc.bat --package python.java.test \\
    PythonToJavaClass.py</pre>
</div>
<p>The first target, <strong>TestPythonToJavaClass.class</strong>, depends on both
<strong>TestPythonToJavaClass.java</strong> and the <strong>PythonToJavaClass.class</strong>, which is the
Python code that&#8217;s converted to a class file. This latter, in turn, depends on
the Python source code. Note that it&#8217;s important that the directory where the
target lives be specified, so that the makefile will create the Java program
with the minimum necessary amount of rebuilding.</p>
</div>
</div>
<div class="section" id="summary">
<h2>Summary<a class="headerlink" href="#summary" title="Permalink to this headline">¶</a></h2>
<p>This chapter has arguably gone much deeper into Jython than required to use the
interpreter design pattern. Indeed, once you decide that you need to use
interpreter and that you&#8217;re not going to get lost inventing your own language,
the solution of installing Jython is quite simple, and you can at least get
started by following the <strong>GreenHouseController</strong> example.</p>
<p>Of course, that example is often too simple and you may need something more
sophisticated, often requiring more interesting data to be passed back and
forth. When I encountered the limited documentation, I felt it necessary to come
up with a more thorough examination of Jython.</p>
<p>In the process, note that there could be another equally powerful design pattern
lurking in here, which could perhaps be called <em>multiple languages</em>. This is
based on the experience of having each language solve a certain class of
problems better than the other; by combining languages you can solve problems
much faster than with either language by itself. CORBA is another way to bridge
across languages, and at the same time bridging between computers and operating
systems.</p>
<p>To me, Python and Java present a very potent combination for program development
because of Java&#8217;s architecture and tool set, and Python&#8217;s extremely rapid
development (generally considered to be 5-10 times faster than C++ or Java).
Python is usually slower, however, but even if you end up re-coding parts of
your program for speed, the initial fast development will allow you to more
quickly flesh out the system and uncover and solve the critical sections. And
often, the execution speed of Python is not a problem - in those cases it&#8217;s an
even bigger win. A number of commercial products already use Java and Jython,
and because of the terrific productivity leverage I expect to see this happen
more in the future.</p>
</div>
<div class="section" id="exercises">
<h2>Exercises<a class="headerlink" href="#exercises" title="Permalink to this headline">¶</a></h2>
<ol class="arabic simple">
<li>Modify <strong>GreenHouseLanguage.py</strong> so that it checks the times for the events
and runs those events at the appropriate times.</li>
<li>Modify <strong>GreenHouseLanguage.py</strong> so that it calls a function for <strong>action</strong>
instead of just printing a string.</li>
<li>Create a Swing application with a <strong>JTextField</strong> (where the user will enter
commands) and a <strong>JTextArea</strong> (where the command results will be displayed).
Connect to a <strong>PythonInterpreter</strong> object so that the output will be sent to
the <strong>JTextArea</strong> (which should scroll). You&#8217;ll need to locate the
<strong>PythonInterpreter</strong> command that redirects the output to a Java stream.</li>
<li>Modify <strong>GreenHouseLanguage.py</strong> to add a master controller class (instead
of the static array inside <strong>Event</strong>) and provide a <strong>run( )</strong> method for
each of the subclasses. Each <strong>run( )</strong> should create and use an object from
the standard Java library during its execution. Modify
<strong>GreenHouseController.java</strong> to use this new class.</li>
<li>Modify the resulting <strong>GreenHouseLanguage.py</strong> from exercise two to produce
Java classes (add the &#64;sig documentation strings to produce the correct Java
signatures, and create a makefile to build the Java <strong>.class</strong> files). Write
a Java program that uses these classes.</li>
</ol>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>The original version of this was called <em>JPython</em>, but the project
changed and the name was changed to emphasize the distinctness of the new
version.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>Changing the registry setting <strong>python.security.respectJavaAccessibility
= true</strong> to <strong>false</strong> makes testing even more powerful because it allows
the test script to use <em>all</em> methods, even protected and package-
private.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <p class="logo"><a href="index.html">
              <img class="logo" src="_static/Logo.png" alt="Logo"/>
            </a></p>
    <font color="Red">This book is in early development; you will find parts that are incorrect &amp; incomplete.</font>
    
            <h3><a href="index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">Jython</a><ul>
<li><a class="reference external" href="#interpreter-motivation">Interpreter Motivation</a></li>
<li><a class="reference external" href="#creating-a-language">Creating a Language</a></li>
<li><a class="reference external" href="#controlling-the-interpreter">Controlling the Interpreter</a><ul>
<li><a class="reference external" href="#putting-data-in">Putting Data In</a></li>
<li><a class="reference external" href="#getting-data-out">Getting Data Out</a></li>
<li><a class="reference external" href="#multiple-interpreters">Multiple Interpreters</a></li>
</ul>
</li>
<li><a class="reference external" href="#controlling-java-from-jython">Controlling Java from Jython</a><ul>
<li><a class="reference external" href="#inner-classes">Inner Classes</a></li>
</ul>
</li>
<li><a class="reference external" href="#using-java-libraries">Using Java libraries</a><ul>
<li><a class="reference external" href="#inheriting-from-java-library-classes">Inheriting from Java library Classes</a></li>
</ul>
</li>
<li><a class="reference external" href="#creating-java-classes-with-jython">Creating Java classes with Jython</a><ul>
<li><a class="reference external" href="#building-java-classes-from-python">Building Java Classes from Python</a></li>
</ul>
</li>
<li><a class="reference external" href="#summary">Summary</a></li>
<li><a class="reference external" href="#exercises">Exercises</a></li>
</ul>
</li>
</ul>


            <h4>Previous topic</h4>
            <p class="topless"><a href="CoroutinesAndConcurrency.html" title="previous chapter">Coroutines &amp; Concurrency</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="Part2.html" title="next chapter">Part II: Idioms</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="_sources/jython.txt">Show Source</a></li>
            </ul>
    
          <h3>Quick search</h3>
            <form class="search" action="search.html" method="get">
              <input type="text" name="q" size="18" /> <input type="submit" value="Go" />
              <input type="hidden" name="check_keywords" value="yes" />
              <input type="hidden" name="area" value="default" />
            </form>
    <h4><a href="http://www.mindviewinc.com/Books/Python3Patterns/Index.php">Project Homepage</a></h4>
    <h4><a href="http://www.bitbucket.org/BruceEckel/python-3-patterns-idioms/issues/">Corrections/Suggestions</a></h4>
    <h4><a href="http://www.mindviewinc.com/Consulting/Index.php">Consulting &amp; Training</a></h4><br><br>

        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="Part2.html" title="Part II: Idioms"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="CoroutinesAndConcurrency.html" title="Coroutines &amp; Concurrency"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">Python 3 Patterns & Idioms</a> &raquo;</li>
      </ul>
    </div>
    <div class="footer">
      &copy; Copyright 2008, Creative Commons Attribution-Share Alike 3.0.
      Last updated on Nov 11, 2008.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.5.
    </div>
  </body>
</html>