This repository has been archived by the owner on Jul 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backporting-python-3-code-to-python-27.html
654 lines (555 loc) · 33 KB
/
backporting-python-3-code-to-python-27.html
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
<!DOCTYPE html>
<html lang="fr"
>
<head>
<title>Backporting python 3 code to python 2.7 - Morphogénie Logiciels</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
/*some stuff for output/input prompts*/
div.cell{border:1px solid transparent;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch}div.cell.selected{border-radius:4px;border:thin #ababab solid}
div.cell.edit_mode{border-radius:4px;border:thin #008000 solid}
div.cell{width:100%;padding:5px 5px 5px 0;margin:0;outline:none}
div.prompt{min-width:11ex;padding:.4em;margin:0;font-family:monospace;text-align:right;line-height:1.21429em}
@media (max-width:480px){div.prompt{text-align:left}}div.inner_cell{display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch;-webkit-box-flex:1;-moz-box-flex:1;box-flex:1;flex:1}
div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;line-height:1.21429em}
div.prompt:empty{padding-top:0;padding-bottom:0}
div.input{page-break-inside:avoid;display:-webkit-box;-webkit-box-orient:horizontal;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:horizontal;-moz-box-align:stretch;display:box;box-orient:horizontal;box-align:stretch;}
div.inner_cell{width:90%;}
div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;}
div.input_prompt{color:navy;border-top:1px solid transparent;}
div.output_wrapper{margin-top:5px;position:relative;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;}
div.output_scroll{height:24em;width:100%;overflow:auto;border-radius:4px;-webkit-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);-moz-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);}
div.output_collapsed{margin:0px;padding:0px;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;}
div.out_prompt_overlay{height:100%;padding:0px 0.4em;position:absolute;border-radius:4px;}
div.out_prompt_overlay:hover{-webkit-box-shadow:inset 0 0 1px #000000;-moz-box-shadow:inset 0 0 1px #000000;box-shadow:inset 0 0 1px #000000;background:rgba(240, 240, 240, 0.5);}
div.output_prompt{color:darkred;}
a.anchor-link:link{text-decoration:none;padding:0px 20px;visibility:hidden;}
h1:hover .anchor-link,h2:hover .anchor-link,h3:hover .anchor-link,h4:hover .anchor-link,h5:hover .anchor-link,h6:hover .anchor-link{visibility:visible;}
/* end stuff for output/input prompts*/
.highlight-ipynb .hll { background-color: #ffffcc }
.highlight-ipynb { background: #f8f8f8; }
.highlight-ipynb .c { color: #408080; font-style: italic } /* Comment */
.highlight-ipynb .err { border: 1px solid #FF0000 } /* Error */
.highlight-ipynb .k { color: #008000; font-weight: bold } /* Keyword */
.highlight-ipynb .o { color: #666666 } /* Operator */
.highlight-ipynb .cm { color: #408080; font-style: italic } /* Comment.Multiline */
.highlight-ipynb .cp { color: #BC7A00 } /* Comment.Preproc */
.highlight-ipynb .c1 { color: #408080; font-style: italic } /* Comment.Single */
.highlight-ipynb .cs { color: #408080; font-style: italic } /* Comment.Special */
.highlight-ipynb .gd { color: #A00000 } /* Generic.Deleted */
.highlight-ipynb .ge { font-style: italic } /* Generic.Emph */
.highlight-ipynb .gr { color: #FF0000 } /* Generic.Error */
.highlight-ipynb .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.highlight-ipynb .gi { color: #00A000 } /* Generic.Inserted */
.highlight-ipynb .go { color: #888888 } /* Generic.Output */
.highlight-ipynb .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
.highlight-ipynb .gs { font-weight: bold } /* Generic.Strong */
.highlight-ipynb .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.highlight-ipynb .gt { color: #0044DD } /* Generic.Traceback */
.highlight-ipynb .kc { color: #008000; font-weight: bold } /* Keyword.Constant */
.highlight-ipynb .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
.highlight-ipynb .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
.highlight-ipynb .kp { color: #008000 } /* Keyword.Pseudo */
.highlight-ipynb .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
.highlight-ipynb .kt { color: #B00040 } /* Keyword.Type */
.highlight-ipynb .m { color: #666666 } /* Literal.Number */
.highlight-ipynb .s { color: #BA2121 } /* Literal.String */
.highlight-ipynb .na { color: #7D9029 } /* Name.Attribute */
.highlight-ipynb .nb { color: #008000 } /* Name.Builtin */
.highlight-ipynb .nc { color: #0000FF; font-weight: bold } /* Name.Class */
.highlight-ipynb .no { color: #880000 } /* Name.Constant */
.highlight-ipynb .nd { color: #AA22FF } /* Name.Decorator */
.highlight-ipynb .ni { color: #999999; font-weight: bold } /* Name.Entity */
.highlight-ipynb .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
.highlight-ipynb .nf { color: #0000FF } /* Name.Function */
.highlight-ipynb .nl { color: #A0A000 } /* Name.Label */
.highlight-ipynb .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
.highlight-ipynb .nt { color: #008000; font-weight: bold } /* Name.Tag */
.highlight-ipynb .nv { color: #19177C } /* Name.Variable */
.highlight-ipynb .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
.highlight-ipynb .w { color: #bbbbbb } /* Text.Whitespace */
.highlight-ipynb .mf { color: #666666 } /* Literal.Number.Float */
.highlight-ipynb .mh { color: #666666 } /* Literal.Number.Hex */
.highlight-ipynb .mi { color: #666666 } /* Literal.Number.Integer */
.highlight-ipynb .mo { color: #666666 } /* Literal.Number.Oct */
.highlight-ipynb .sb { color: #BA2121 } /* Literal.String.Backtick */
.highlight-ipynb .sc { color: #BA2121 } /* Literal.String.Char */
.highlight-ipynb .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
.highlight-ipynb .s2 { color: #BA2121 } /* Literal.String.Double */
.highlight-ipynb .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
.highlight-ipynb .sh { color: #BA2121 } /* Literal.String.Heredoc */
.highlight-ipynb .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
.highlight-ipynb .sx { color: #008000 } /* Literal.String.Other */
.highlight-ipynb .sr { color: #BB6688 } /* Literal.String.Regex */
.highlight-ipynb .s1 { color: #BA2121 } /* Literal.String.Single */
.highlight-ipynb .ss { color: #19177C } /* Literal.String.Symbol */
.highlight-ipynb .bp { color: #008000 } /* Name.Builtin.Pseudo */
.highlight-ipynb .vc { color: #19177C } /* Name.Variable.Class */
.highlight-ipynb .vg { color: #19177C } /* Name.Variable.Global */
.highlight-ipynb .vi { color: #19177C } /* Name.Variable.Instance */
.highlight-ipynb .il { color: #666666 } /* Literal.Number.Integer.Long */
</style>
<style type="text/css">
/* Overrides of notebook CSS for static HTML export */
div.entry-content {
overflow: visible;
padding: 8px;
}
.input_area {
padding: 0.2em;
}
a.heading-anchor {
white-space: normal;
}
.rendered_html
code {
font-size: .8em;
}
pre.ipynb {
color: black;
background: #f7f7f7;
border: none;
box-shadow: none;
margin-bottom: 0;
padding: 0;
margin: 0px;
font-size: 13px;
}
/* remove the prompt div from text cells */
div.text_cell .prompt {
display: none;
}
/* remove horizontal padding from text cells, */
/* so it aligns with outer body text */
div.text_cell_render {
padding: 0.5em 0em;
}
img.anim_icon{padding:0; border:0; vertical-align:middle; -webkit-box-shadow:none; -box-shadow:none}
</style>
<script src="https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script>
<script type="text/javascript">
init_mathjax = function() {
if (window.MathJax) {
// MathJax loaded
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
},
displayAlign: 'left', // Change this to 'center' to center equations.
"HTML-CSS": {
styles: {'.MathJax_Display': {"margin": 0}}
}
});
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}
}
init_mathjax();
</script>
<link href="http://morphogenie.fr/images/favicon.png" rel="icon">
<link rel="canonical" href="http://morphogenie.fr/backporting-python-3-code-to-python-27.html">
<meta name="author" content="Guillaume Gay" />
<meta name="keywords" content="python,3to2" />
<meta name="description" content="An adventure in backporting, unfiltered for stupid mistakes" />
<!-- Bootstrap -->
<link rel="stylesheet" href="http://morphogenie.fr/theme/css/bootstrap.cosmo.min.css" type="text/css"/>
<link href="http://morphogenie.fr/theme/css/font-awesome.min.css" rel="stylesheet">
<link href="http://morphogenie.fr/theme/css/pygments/native.css" rel="stylesheet">
<link href="http://morphogenie.fr/theme/css/typogrify.css" rel="stylesheet">
<link rel="stylesheet" href="http://morphogenie.fr/theme/css/style.css" type="text/css"/>
<link href="http://morphogenie.fr/feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
title="Morphogénie Logiciels ATOM Feed"/>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-left">
<a href="http://morphogenie.fr/" class="navbar-brand">
<img align="left" src="http://morphogenie.fr/images/logo_blackbg.png" width=""/> </a>
</div>
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="/pages/aboutus.html">About Morphogénie</a></li>
<li><a href="/pages/projects.html">Projects</a></li>
<li><a href="/pages/what-we-do.html">Services</a></li>
<li><a href="/pages/tools.html">Tools</a></li>
<li><a href="/pages/contact.html">Contact</a></li>
<li class="active">
<a href="http://morphogenie.fr/category/misc.html">Misc</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="http://morphogenie.fr/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<div class="container">
<div class="row">
<div class="col-sm-9">
<section id="content">
<article>
<header class="page-header">
<h1>
<a href="http://morphogenie.fr/backporting-python-3-code-to-python-27.html"
rel="bookmark"
title="Permalink to Backporting python 3 code to python 2.7">
Backporting python 3 code to python 2.7
</a>
</h1>
</header>
<div class="entry-content">
<div class="panel">
<div class="panel-body">
<footer class="post-info">
<span class="label label-default">Date</span>
<span class="published">
<i class="fa fa-calendar"></i><time datetime="2014-04-23T00:00:00+02:00"> mer. 23 avril 2014</time>
</span>
<span class="label label-default">Tags</span>
<a href="http://morphogenie.fr/tag/python.html">python</a>
/
<a href="http://morphogenie.fr/tag/3to2.html">3to2</a>
</footer><!-- /.post-info --> </div>
</div>
<p>We decided to develop
<a href="https://github.com/bnoi/scikit-tracker">scikit_tracker</a> in python 3.x,
and test only against this brand of python, because all the Scipy
stack is ported now, so why not.</p>
<p>Unfortunately, our first user (whom we don’t want to scare off) uses
<a href="https://www.enthought.com/products/canopy/">canopy</a>, which is python 2.7.</p>
<p>So I thought I would document the porting of the code, so here we go.</p>
<!-- TEASER_END -->
<h2>A script to put a correct header on top of each file.</h2>
<p>Adding <code>__from__ future import ...</code> statements on top of your file goes
a long way in porting the code, making most of the new feature from
python 3 available to 2.x code.</p>
<p>I’m sure there’s a <code>sed</code> one liner to do that, but I’m just more efficient with python:</p>
<h3>Recursively find all the python file in the project’s directory</h3>
<div class="highlight"><pre><span></span><span class="n">pyfiles</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">root</span><span class="p">,</span> <span class="n">subFolders</span><span class="p">,</span> <span class="n">files</span> <span class="ow">in</span> <span class="n">os</span><span class="o">.</span><span class="n">walk</span><span class="p">(</span><span class="n">base_dir</span><span class="p">):</span>
<span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">files</span><span class="p">:</span>
<span class="k">if</span> <span class="n">f</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">'.py'</span><span class="p">):</span>
<span class="n">pyfiles</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">base_dir</span><span class="p">,</span> <span class="n">root</span><span class="p">,</span> <span class="n">f</span><span class="p">))</span>
</pre></div>
<h3>Check we really got files:</h3>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="k">print</span><span class="p">(</span><span class="s1">'''All files ok: {}'''</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">all</span><span class="p">([</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">fname</span><span class="p">)</span>
<span class="k">for</span> <span class="n">fname</span> <span class="ow">in</span> <span class="n">pyfiles</span><span class="p">])))</span>
</pre></div>
<p>Adding imports and coding on top of the python files.
<strong><span class="caps">TODO</span></strong>: avoid adding this if it’s allready there…</p>
<div class="highlight"><pre><span></span><span class="n">compat_string</span> <span class="o">=</span> <span class="s1">'''# -*- coding: utf-8 -*-</span>
<span class="s1">from __future__ import unicode_literals</span>
<span class="s1">from __future__ import division</span>
<span class="s1">from __future__ import absolute_import</span>
<span class="s1">from __future__ import print_function</span>
<span class="s1">'''</span>
<span class="k">for</span> <span class="n">fname</span> <span class="ow">in</span> <span class="n">pyfiles</span><span class="p">:</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">fname</span><span class="p">,</span> <span class="s1">'r+'</span><span class="p">)</span> <span class="k">as</span> <span class="n">pyfile</span><span class="p">:</span>
<span class="n">new_f</span> <span class="o">=</span> <span class="s1">''</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">compat_string</span><span class="p">]</span><span class="o">+</span>
<span class="p">[</span><span class="n">line</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">pyfile</span><span class="o">.</span><span class="n">readlines</span><span class="p">()])</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">fname</span><span class="p">,</span> <span class="s1">'w+'</span><span class="p">)</span> <span class="k">as</span> <span class="n">pyfile</span><span class="p">:</span>
<span class="n">pyfile</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">new_f</span><span class="p">)</span>
</pre></div>
<p>We use <code>UserDict</code>to subclass dictionnaries, we need to modify import so I replaced this:</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">UserDict</span>
</pre></div>
<p>by that:</p>
<div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">version_info</span> <span class="o">></span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">0</span><span class="p">):</span>
<span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">UserDict</span>
<span class="k">else</span><span class="p">:</span>
<span class="kn">from</span> <span class="nn">UserDict</span> <span class="kn">import</span> <span class="n">UserDict</span>
</pre></div>
<h2>Using 3to2</h2>
<p>We don’t really want to do all the fixes provided by 3to2, as we only seek python 2.7 compatibility</p>
<p>Here is the list of possible fixes, and a comment on what it does when passed :</p>
<div class="highlight"><pre><span></span>/home/user $ 3to2 -l
Checking Python version info... <span class="m">2</span>.7.5
Available transformations <span class="k">for</span> the -f/--fix option:
annotations <span class="c1"># says no file need modification</span>
bitlength <span class="c1"># says no file need modification</span>
bytes <span class="c1"># Only wants to modify tifffile.py and I know it works fine in both versions</span>
classdecorator <span class="c1"># says no file need modification</span>
collections <span class="c1"># messes with the correction above, which is version agnostic</span>
dctsetcomp <span class="c1"># that's dict comprehension, which was backported to python 2.7</span>
division <span class="c1"># says no file need modification</span>
except <span class="c1"># Only wants to modify tifffile.py and I know it works fine in both versions</span>
features <span class="c1"># says no file need modification</span>
fullargspec <span class="c1"># says no file need modification</span>
funcattrs <span class="c1"># says no file need modification</span>
getcwd <span class="c1"># says no file need modification</span>
imports <span class="c1"># says no file need modification</span>
imports2 <span class="c1"># says no file need modification</span>
input <span class="c1"># says no file need modification</span>
int <span class="c1"># Appends an L to all the ints (I guess because all ints are long ints in py3k)</span>
intern <span class="c1"># says no file need modification</span>
itertools <span class="c1"># changes zip to izip, but that's not interesting for us (py 2.7 ok I think)</span>
kwargs <span class="c1"># says no file need modification</span>
memoryview <span class="c1"># says no file need modification</span>
metaclass <span class="c1"># says no file need modification</span>
methodattrs <span class="c1"># says no file need modification</span>
newstyle <span class="c1">### This one is usefull, adds (object) to the class definition</span>
next <span class="c1"># Only wants to modify tifffile.py and I know it works fine in both versions</span>
numliterals <span class="c1"># says no file need modification</span>
open <span class="c1">## Backported</span>
print <span class="c1">## Fixed by from __future__</span>
printfunction <span class="c1"># says no file need modification</span>
raise <span class="c1"># says no file need modification</span>
range <span class="c1">## Keep range for py3 compatibility</span>
reduce <span class="c1"># says no file need modification</span>
setliteral <span class="c1"># says no file need modification</span>
str <span class="c1">## Fixed by from __future__</span>
super <span class="c1">#### Usefull</span>
throw <span class="c1"># says no file need modification</span>
unittest <span class="c1"># says no file need modification</span>
unpacking <span class="c1"># says no file need modification</span>
with <span class="c1"># New in 2.5</span>
</pre></div>
<p>Let’s resume all that:</p>
<ul>
<li>Usefull fixes:</li>
</ul>
<div class="highlight"><pre><span></span>newstyle, super
</pre></div>
<ul>
<li>Fixes that don’t do anything:</li>
</ul>
<div class="highlight"><pre><span></span>annotations, bitlength, classdecorator, division, features,
fullargspec, funcattrs, getcwd, imports, imports2, input, intern, kwargs,
memoryview, metaclass, methodattrs, numliterals, printfunction, raise,
reduce, setliteral, throw, unittest, unpacking
</pre></div>
<ul>
<li>Fixes that would modify <code>tifffile.py</code> only (we don’t want those):</li>
</ul>
<div class="highlight"><pre><span></span>bytes, except, next
</pre></div>
<ul>
<li>Fixes that are corrected by <code>from __future__ import ...</code>:</li>
</ul>
<div class="highlight"><pre><span></span>print, str
</pre></div>
<ul>
<li>Fixes that are unnecessary with python 2.7:</li>
</ul>
<div class="highlight"><pre><span></span>dctsetcomp, itertools <span class="o">(</span>?<span class="o">)</span>, open, with
</pre></div>
<p>So now we just issue this command to port the code:</p>
<div class="highlight"><pre><span></span>/home/user$ 3to2 -f super -f newstyle -w sktracker/ <span class="c1">## This is our project's directory</span>
</pre></div>
<h2>Cleaning</h2>
<p>Once this is done, there’s quite a lot of work to fix, and have tests passing (by the way, tests are really great, seeing how many quirks I had to fix).</p>
<p>Now let’s go through the diff to see what we had to change.</p>
<ul>
<li>This of course is here everywhere:</li>
</ul>
<div class="highlight"><pre><span></span><span class="gi">+# -*- coding: utf-8 -*-</span>
<span class="gi">+</span>
<span class="gi">+</span>
<span class="gi">+from __future__ import unicode_literals</span>
<span class="gi">+from __future__ import division</span>
<span class="gi">+from __future__ import absolute_import</span>
<span class="gi">+from __future__ import print_function</span>
</pre></div>
<ul>
<li>Pytables HDFStore files can’t be exchanged between python 2 and python 3, so we have to have two samples files for the tests</li>
</ul>
<div class="highlight"><pre><span></span> import tempfile
import shutil
import pandas as pd
<span class="gi">+import sys</span>
from ..io.utils import load_img_list
def sample_h5():
"""
"""
<span class="gi">+ if sys.version_info[0] < 3:</span>
<span class="gi">+ return os.path.join(data_path, "sample_py2.h5")</span>
return os.path.join(data_path, "sample.h5")
</pre></div>
<ul>
<li>There I guess <code>subprocess</code> is inconsistent. I think this is relatively harmless</li>
</ul>
<div class="highlight"><pre><span></span> # module such as numpy (only needed on linux)
if os.name == 'posix':
subprocess.call("taskset -p 0xff %d" % os.getpid(),
<span class="gd">- shell=True, stdout=subprocess.DEVNULL)</span>
<span class="gi">+ shell=True)#, stdout=subprocess.DEVNULL) ## Py2.7 compat</span>
</pre></div>
<ul>
<li>This is rather self explanatory</li>
</ul>
<div class="highlight"><pre><span></span><span class="gd">-from collections import UserDict</span>
<span class="gi">+if sys.version_info[0] > 2:</span>
<span class="gi">+ from collections import UserDict</span>
<span class="gi">+else:</span>
<span class="gi">+ from UserDict import UserDict</span>
<span class="gi">+</span>
</pre></div>
<ul>
<li>Old style / new style classes (there are other like that)</li>
</ul>
<div class="highlight"><pre><span></span><span class="gd">-class ObjectsIO():</span>
<span class="gi">+class ObjectsIO(object):</span>
</pre></div>
<ul>
<li>This one had to be called like that, not through <code>super</code>, maybe because <code>UserDict</code> is old style</li>
</ul>
<div class="highlight"><pre><span></span> def __init__(self, metadata_dict, objectsio):
self.objectsio = objectsio
<span class="gd">- super().__init__(metadata_dict)</span>
<span class="gi">+ UserDict.__init__(self, metadata_dict)</span>
</pre></div>
<ul>
<li>Now that one involved really obscure utf-8 / unicode shenaningans, plus <code>io.StringIO</code> not working with 2.7, while creating a temp file was not with 3…</li>
</ul>
<p>So here is what the solution looks like:</p>
<div class="highlight"><pre><span></span> et = ElementTree.ElementTree(self.root)
<span class="gd">- f = io.StringIO()</span>
<span class="gd">- et.write(f, encoding='unicode', xml_declaration=True,</span>
<span class="gd">- default_namespace=None)</span>
<span class="gd">- output = f.getvalue()</span>
<span class="gi">+ if sys.version_info[0] < 3:</span>
<span class="gi">+ f = tempfile.NamedTemporaryFile()</span>
<span class="gi">+ et.write(f, encoding='utf-8', xml_declaration=True,</span>
<span class="gi">+ default_namespace=None)</span>
<span class="gi">+ f.seek(0)</span>
<span class="gi">+ output = ''.join(f.readlines())</span>
<span class="gi">+ else:</span>
<span class="gi">+ f = io.StringIO()</span>
<span class="gi">+ et.write(f, encoding='unicode', xml_declaration=True,</span>
<span class="gi">+ default_namespace=None)</span>
<span class="gi">+ output = f.getvalue()</span>
f.close()
</pre></div>
<ul>
<li>I don’t realy know why, but I had to explicitely use <code>BrownianLinkCostFunction</code> here, and not the automated <code>self.__class__</code></li>
</ul>
<div class="highlight"><pre><span></span><span class="gd">- super().__init__(context={}, parameters=_parameters)</span>
<span class="gi">+ super(BrownianLinkCostFunction, self).__init__(context={}, parameters=_parameters)</span>
</pre></div>
<ul>
<li>Unicode / string mess, I didn’t really fix it up yet…</li>
</ul>
<div class="highlight"><pre><span></span><span class="gd">- cost_func.check_context('test_string', str)</span>
<span class="gi">+ ### This fails in py2.7</span>
<span class="gi">+ if sys.version_info[0] > 2:</span>
<span class="gi">+ cost_func.check_context('test_string', str)</span>
</pre></div>
<ul>
<li>More encoding quirks (makes you <em>love</em> python 3):</li>
</ul>
<div class="highlight"><pre><span></span> if message:
<span class="gd">- bar += " " + str(message)</span>
<span class="gi">+ bar = " ".join([bar, message])</span>
</pre></div>
<p>And now all the tests are passing, which is great, have to try to get
into production now. There are still some quirks to fix (essentially anytime we call <code>str</code>).</p>
</div>
<!-- /.entry-content -->
<hr/>
<section class="comments" id="comments">
<h2>Comments</h2>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'damcellbiology'; // required: replace example with your forum shortname
var disqus_identifier = 'backporting-python-3-code-to-python-27';
var disqus_url = 'http://morphogenie.fr/backporting-python-3-code-to-python-27.html';
var disqus_config = function () {
this.language = "fr";
};
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by
Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</section>
</article>
</section>
</div>
<div class="col-sm-3 well well-sm" id="sidebar">
<aside>
<section>
<ul class="list-group list-group-flush">
<li class="list-group-item"><h4><i class="fa fa-external-link-square fa-lg"></i><span class="icon-label">Links</span></h4>
<ul class="list-group" id="links">
<li class="list-group-item">
<a href="http://scipy.org/" target="_blank">
Scipy
</a>
</li>
<li class="list-group-item">
<a href="http://python.org/" target="_blank">
Python.org
</a>
</li>
</ul>
</li>
<li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4>
<ul class="list-group" id="social">
<li class="list-group-item"><a href="https://github.com/DamCB"><i class="fa fa-github-square fa-lg"></i> GitHub</a></li>
<li class="list-group-item"><a href="https://twitter.com/MorphoLG"><i class="fa fa-twitter-square fa-lg"></i> Twitter</a></li>
</ul>
</li>
<li class="list-group-item"><a href="http://morphogenie.fr/"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a>
<ul class="list-group " id="tags">
</ul>
</li>
</ul>
</section>
</aside> </div>
</div>
</div>
<footer>
<div class="container">
<hr>
<div class="row">
<div class="col-xs-10">© 2016 Guillaume Gay
· Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>,
<a href="http://docs.getpelican.com/" target="_blank">Pelican</a>,
<a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div>
<div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div>
</div>
</div>
</footer>
<script src="http://morphogenie.fr/theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://morphogenie.fr/theme/js/bootstrap.min.js"></script>
<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="http://morphogenie.fr/theme/js/respond.min.js"></script>
<!-- Disqus -->
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'damcellbiology'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var s = document.createElement('script');
s.async = true;
s.type = 'text/javascript';
s.src = '//' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
</script>
<!-- End Disqus Code -->
</body>
</html>