forked from RafeKettler/magicmethods
-
Notifications
You must be signed in to change notification settings - Fork 0
/
magicmethods.html
773 lines (700 loc) · 59.2 KB
/
magicmethods.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
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
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>A Guide to Python's Magic Methods « rafekettler.com</title>
<meta name="description" content="A guide to all the Magic Methods in Python" />
<meta name="keywords" content="python, programming, magic methods, object-oriented, oop" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<h1>A Guide to Python's Magic Methods</h1>
<h3>Rafe Kettler</h3>
<p>Copyright © 2012 Rafe Kettler</p>
<p>Version 1.17</p>
<p>A PDF version of this guide can be obtained from <a href="http://www.rafekettler.com/magicmethods.pdf">my site</a> or <a href="https://github.com/RafeKettler/magicmethods/raw/master/magicmethods.pdf">Github</a>. The magic methods guide has <a href="http://www.github.com/RafeKettler/magicmethods">a git repository at http://www.github.com/RafeKettler/magicmethods</a>. Any issues can be reported
there, along with comments, (or even contributions!).</p>
<p><strong><a id="table" href="#table">Table of Contents</a></strong></p>
<ol>
<li><a href="#intro">Introduction</a></li>
<li><a href="#construction">Construction and Initialization</a></li>
<li><a href="#operators">Making Operators Work on Custom Classes</a><ul>
<li><a href="#comparisons">Comparison magic methods</a></li>
<li><a href="#numeric">Numeric magic methods</a></li>
</ul>
</li>
<li><a href="#representations">Representing your Classes</a></li>
<li><a href="#access">Controlling Attribute Access</a></li>
<li><a href="#sequence">Making Custom Sequences</a></li>
<li><a href="#reflection">Reflection</a></li>
<li><a href="#abcs">Abstract Base Classes</a> </li>
<li><a href="#callable">Callable Objects</a></li>
<li><a href="#context">Context Managers</a></li>
<li><a href="#descriptor">Building Descriptor Objects</a></li>
<li><a href="#copying">Copying</a></li>
<li><a href="#pickling">Pickling your Objects</a></li>
<li><a href="#conclusion">Conclusion</a></li>
<li><a href="#appendix1">Appendix 1: How to Call Magic Methods</a></li>
<li><a href="#appendix2">Appendix 2: Changes in Python 3</a></li>
</ol><h2><a id="intro" href="#intro">Introduction</a></h2>
<p>This guide is the culmination of a few months' worth of blog posts. The subject is <strong>magic methods</strong>.</p>
<p>What are magic methods? They're everything in object-oriented Python. They're special methods that you can define to add "magic" to your classes. They're always surrounded by double underscores (e.g. <code>__init__</code> or <code>__lt__</code>). They're also not as well documented as they need to be. All of the magic methods for Python appear in the same section in the Python docs, but they're scattered about and only loosely organized. There's hardly an example to be found in that section (and that may very well be by design, since they're all detailed in the <em>language reference</em>, along with boring syntax descriptions, etc.).</p>
<p>So, to fix what I perceived as a flaw in Python's documentation, I set out to provide some more plain-English, example-driven documentation for Python's magic methods. I started out with weekly blog posts, and now that I've finished with those, I've put together this guide.</p>
<p>I hope you enjoy it. Use it as a tutorial, a refresher, or a reference; it's just intended to be a user-friendly guide to Python's magic methods.</p>
<h2><a id="construction" href="#construction">Construction and Initialization</a></h2>
<p>Everyone knows the most basic magic method, <code>__init__</code>. It's the way that we can define the initialization behavior of an object. However, when I call <code>x = SomeClass()</code>, <code>__init__</code> is not the first thing to get called. Actually, it's a method called <code>__new__</code>, which actually creates the instance, then passes any arguments at creation on to the initializer. At the other end of the object's lifespan, there's <code>__del__</code>. Let's take a closer look at these 3 magic methods:</p>
<dl>
<dt><code>__new__(cls, [...)</code></dt>
<dd><code>__new__</code> is the first method to get called in an object's instantiation. It takes the class, then any other arguments that it will pass along to <code>__init__</code>. <code>__new__</code> is used fairly rarely, but it does have its purposes, particularly when subclassing an immutable type like a tuple or a string. I don't want to go in to too much detail on <code>__new__</code> because it's not too useful, but it is covered in great detail <a href="http://www.python.org/download/releases/2.2/descrintro/#__new__">in the Python docs</a>.</dd>
<dt><code>__init__(self, [...)</code></dt>
<dd>The initializer for the class. It gets passed whatever the primary constructor was called with (so, for example, if we called <code>x = SomeClass(10, 'foo')</code>, <code>__init__</code> would get passed <code>10</code> and <code>'foo'</code> as arguments. <code>__init__</code> is almost universally used in Python class definitions.</dd>
<dt><code>__del__(self)</code></dt>
<dd>If <code>__new__</code> and <code>__init__</code> formed the constructor of the object, <code>__del__</code> is the destructor. It doesn't implement behavior for the statement <code>del x</code> (so that code would not translate to <code>x.__del__()</code>). Rather, it defines behavior for when an object is garbage collected. It can be quite useful for objects that might require extra cleanup upon deletion, like sockets or file objects. Be careful, however, as there is no guarantee that <code>__del__</code> will be executed if the object is still alive when the interpreter exits, so <code>__del__</code> can't serve as a replacement for good coding practices (like always closing a connection when you're done with it. In fact, <code>__del__</code> should almost never be used because of the precarious circumstances under which it is called; use it with caution!</dd>
</dl>
<p>Putting it all together, here's an example of <code>__init__</code> and <code>__del__</code> in action:</p>
<pre class="codehilite"><code class="language-python">from os.path import join
class FileObject:
'''Wrapper for file objects to make sure the file gets closed on deletion.'''
def __init__(self, filepath='~', filename='sample.txt'):
# open a file filename in filepath in read and write mode
self.file = open(join(filepath, filename), 'r+')
def __del__(self):
self.file.close()
del self.file</code></pre>
<h2><a id="operators" href="#operators">Making Operators Work on Custom Classes</a></h2>
<p>One of the biggest advantages of using Python's magic methods is that they provide a simple way to make objects behave like built-in types. That means you can avoid ugly, counter-intuitive, and nonstandard ways of performing basic operators. In some languages, it's common to do something like this:</p>
<pre class="codehilite"><code class="language-python">if instance.equals(other_instance):
# do something</code></pre>
<p>You could certainly do this in Python, too, but this adds confusion and is unnecessarily verbose. Different libraries might use different names for the same operations, making the client do way more work than necessary. With the power of magic methods, however, we can define one method (<code>__eq__</code>, in this case), and say what we <em>mean</em> instead:</p>
<pre class="codehilite"><code class="language-python">if instance == other_instance:
#do something</code></pre>
<p>That's part of the power of magic methods. The vast majority of them allow us to define meaning for operators so that we can use them on our own classes just like they were built in types.</p>
<h3><a id="comparisons" href="#comparisons">Comparison magic methods</a></h3>
<p>Python has a whole slew of magic methods designed to implement intuitive comparisons between objects using operators, not awkward method calls. They also provide a way to override the default Python behavior for comparisons of objects (by reference). Here's the list of those methods and what they do:</p>
<dl>
<dt><code>__cmp__(self, other)</code></dt>
<dd><code>__cmp__</code> is the most basic of the comparison magic methods. It actually implements behavior for all of the comparison operators (<, ==, !=, etc.), but it might not do it the way you want (for example, if whether one instance was equal to another were determined by one criterion and and whether an instance is greater than another were determined by something else). <code>__cmp__</code> should return a negative integer if <code>self < other</code>, zero if <code>self == other</code>, and positive if <code>self > other</code>. It's usually best to define each comparison you need rather than define them all at once, but <code>__cmp__</code> can be a good way to save repetition and improve clarity when you need all comparisons implemented with similar criteria.</dd>
<dt><code>__eq__(self, other)</code></dt>
<dd>Defines behavior for the equality operator, <code>==</code>.</dd>
<dt><code>__ne__(self, other)</code></dt>
<dd>Defines behavior for the inequality operator, <code>!=</code>.</dd>
<dt><code>__lt__(self, other)</code></dt>
<dd>Defines behavior for the less-than operator, <code><</code>.</dd>
<dt><code>__gt__(self, other)</code></dt>
<dd>Defines behavior for the greater-than operator, <code>></code>.</dd>
<dt><code>__le__(self, other)</code></dt>
<dd>Defines behavior for the less-than-or-equal-to operator, <code><=</code>.</dd>
<dt><code>__ge__(self, other)</code></dt>
<dd>Defines behavior for the greater-than-or-equal-to operator, <code>>=</code>.</dd>
</dl>
<p>For an example, consider a class to model a word. We might want to compare words lexicographically (by the alphabet), which is the default comparison behavior for strings, but we also might want to do it based on some other criterion, like length or number of syllables. In this example, we'll compare by length. Here's an implementation:</p>
<pre class="codehilite"><code class="language-python">class Word(str):
'''Class for words, defining comparison based on word length.'''
def __new__(cls, word):
# Note that we have to use __new__. This is because str is an immutable
# type, so we have to initialize it early (at creation)
if ' ' in word:
print "Value contains spaces. Truncating to first space."
word = word[:word.index(' ')] # Word is now all chars before first space
return str.__new__(cls, word)
def __gt__(self, other):
return len(self) > len(other)
def __lt__(self, other):
return len(self) < len(other)
def __ge__(self, other):
return len(self) >= len(other)
def __le__(self, other):
return len(self) <= len(other)</code></pre>
<p>Now, we can create two <code>Word</code>s (by using <code>Word('foo')</code> and <code>Word('bar')</code>) and compare them based on length. Note, however, that we didn't define <code>__eq__</code> and <code>__ne__</code>. This is because this would lead to some weird behavior (notably that <code>Word('foo') == Word('bar')</code> would evaluate to true). It wouldn't make sense to test for equality based on length, so we fall back on <code>str</code>'s implementation of equality.</p>
<p>Now would be a good time to note that you don't have to define every comparison magic method to get rich comparisons. The standard library has kindly provided us with a class decorator in the module <code>functools</code> that will define all rich comparison methods if you only define <code>__eq__</code> and one other (e.g. <code>__gt__</code>, <code>__lt__</code>, etc.) This feature is only available in Python 2.7, but when you get a chance it saves a great deal of time and effort. You can use it by placing <code>@total_ordering</code> above your class definition.</p>
<h3><a id="numeric" href="#numeric">Numeric magic methods</a></h3>
<p>Just like you can create ways for instances of your class to be compared with comparison operators, you can define behavior for numeric operators. Buckle your seat belts, folks...there's a lot of these. For organization's sake, I've split the numeric magic methods into 5 categories: unary operators, normal arithmetic operators, reflected arithmetic operators (more on this later), augmented assignment, and type conversions.</p>
<h4>Unary operators and functions</h4>
<p>Unary operators and functions only have one operand, e.g. negation, absolute value, etc.</p>
<dl>
<dt><code>__pos__(self)</code></dt>
<dd>Implements behavior for unary positive (e.g. <code>+some_object</code>)</dd>
<dt><code>__neg__(self)</code></dt>
<dd>Implements behavior for negation (e.g. <code>-some_object</code>)</dd>
<dt><code>__abs__(self)</code></dt>
<dd>Implements behavior for the built in <code>abs()</code> function.</dd>
<dt><code>__invert__(self)</code></dt>
<dd>Implements behavior for inversion using the <code>~</code> operator. For an explanation on what this does, see <a href="http://en.wikipedia.org/wiki/Bitwise_operation#NOT">the Wikipedia article on bitwise operations</a>.</dd>
<dt><code>__round__(self, n)</code></dt>
<dd>Implements behavior for the built in <code>round()</code> function. <code>n</code> is the number of decimal places to round to.</dd>
<dt><code>__floor__(self)</code></dt>
<dd>Implements behavior for <code>math.floor()</code>, i.e., rounding down to the nearest integer.</dd>
<dt><code>__ceil__(self)</code></dt>
<dd>Implements behavior for <code>math.ceil()</code>, i.e., rounding up to the nearest integer.</dd>
<dt><code>__trunc__(self)</code></dt>
<dd>Implements behavior for <code>math.trunc()</code>, i.e., truncating to an integral.</dd>
</dl>
<h4>Normal arithmetic operators</h4>
<p>Now, we cover the typical binary operators (and a function or two): +, -, * and the like. These are, for the most part, pretty self-explanatory.</p>
<dl>
<dt><code>__add__(self, other)</code></dt>
<dd>Implements addition.</dd>
<dt><code>__sub__(self, other)</code></dt>
<dd>Implements subtraction.</dd>
<dt><code>__mul__(self, other)</code></dt>
<dd>Implements multiplication.</dd>
<dt><code>__floordiv__(self, other)</code></dt>
<dd>Implements integer division using the <code>//</code> operator.</dd>
<dt><code>__div__(self, other)</code></dt>
<dd>Implements division using the <code>/</code> operator.</dd>
<dt><code>__truediv__(self, other)</code></dt>
<dd>Implements <em>true</em> division. Note that this only works when <code>from __future__ import division</code> is in effect.</dd>
<dt><code>__mod__(self, other)</code></dt>
<dd>Implements modulo using the <code>%</code> operator.</dd>
<dt><code>__divmod__(self, other)</code></dt>
<dd>Implements behavior for long division using the <code>divmod()</code> built in function.</dd>
<dt><code>__pow__</code></dt>
<dd>Implements behavior for exponents using the <code>**</code> operator.</dd>
<dt><code>__lshift__(self, other)</code></dt>
<dd>Implements left bitwise shift using the <code><<</code> operator.</dd>
<dt><code>__rshift__(self, other)</code></dt>
<dd>Implements right bitwise shift using the <code>>></code> operator.</dd>
<dt><code>__and__(self, other)</code></dt>
<dd>Implements bitwise and using the <code>&</code> operator.</dd>
<dt><code>__or__(self, other)</code></dt>
<dd>Implements bitwise or using the <code>|</code> operator.</dd>
<dt><code>__xor__(self, other)</code></dt>
<dd>Implements bitwise xor using the <code>^</code> operator.</dd>
</dl>
<h4>Reflected arithmetic operators</h4>
<p>You know how I said I would get to reflected arithmetic in a bit? Some of you might think it's some big, scary, foreign concept. It's actually quite simple. Here's an example:</p>
<pre class="codehilite"><code class="language-python">some_object + other</code></pre>
<p>That was "normal" addition. The reflected equivalent is the same thing, except with the operands switched around:</p>
<pre class="codehilite"><code class="language-python">other + some_object</code></pre>
<p>So, all of these magic methods do the same thing as their normal equivalents, except the perform the operation with other as the first operand and self as the second, rather than the other way around. In most cases, the result of a reflected operation is the same as its normal equivalent, so you may just end up defining <code>__radd__</code> as calling <code>__add__</code> and so on. Note that the object on the left hand side of the operator (<code>other</code> in the example) must not define (or return <code>NotImplemented</code>) for its definition of the non-reflected version of an operation. For instance, in the example, <code>some_object.__radd__</code> will only be called if <code>other</code> does not define <code>__add__</code>.</p>
<dl>
<dt><code>__radd__(self, other)</code></dt>
<dd>Implements reflected addition.</dd>
<dt><code>__rsub__(self, other)</code></dt>
<dd>Implements reflected subtraction.</dd>
<dt><code>__rmul__(self, other)</code></dt>
<dd>Implements reflected multiplication.</dd>
<dt><code>__rfloordiv__(self, other)</code></dt>
<dd>Implements reflected integer division using the <code>//</code> operator.</dd>
<dt><code>__rdiv__(self, other)</code></dt>
<dd>Implements reflected division using the <code>/</code> operator.</dd>
<dt><code>__rtruediv__(self, other)</code></dt>
<dd>Implements reflected <em>true</em> division. Note that this only works when <code>from __future__ import division</code> is in effect.</dd>
<dt><code>__rmod__(self, other)</code></dt>
<dd>Implements reflected modulo using the <code>%</code> operator.</dd>
<dt><code>__rdivmod__(self, other)</code></dt>
<dd>Implements behavior for long division using the <code>divmod()</code> built in function, when <code>divmod(other, self)</code> is called.</dd>
<dt><code>__rpow__</code></dt>
<dd>Implements behavior for reflected exponents using the <code>**</code> operator.</dd>
<dt><code>__rlshift__(self, other)</code></dt>
<dd>Implements reflected left bitwise shift using the <code><<</code> operator.</dd>
<dt><code>__rrshift__(self, other)</code></dt>
<dd>Implements reflected right bitwise shift using the <code>>></code> operator.</dd>
<dt><code>__rand__(self, other)</code></dt>
<dd>Implements reflected bitwise and using the <code>&</code> operator.</dd>
<dt><code>__ror__(self, other)</code></dt>
<dd>Implements reflected bitwise or using the <code>|</code> operator.</dd>
<dt><code>__rxor__(self, other)</code></dt>
<dd>Implements reflected bitwise xor using the <code>^</code> operator.</dd>
</dl>
<h4>Augmented assignment</h4>
<p>Python also has a wide variety of magic methods to allow custom behavior to be defined for augmented assignment. You're probably already familiar with augmented assignment, it combines "normal" operators with assignment. If you still don't know what I'm talking about, here's an example:</p>
<pre class="codehilite"><code class="language-python">x = 5
x += 1 # in other words x = x + 1</code></pre>
<p>Each of these methods should return the value that the variable on the left hand side should be assigned to (for instance, for <code>a += b</code>, <code>__iadd__</code> might return <code>a + b</code>, which would be assigned to <code>a</code>). Here's the list:</p>
<dl>
<dt><code>__iadd__(self, other)</code></dt>
<dd>Implements addition with assignment.</dd>
<dt><code>__isub__(self, other)</code></dt>
<dd>Implements subtraction with assignment.</dd>
<dt><code>__imul__(self, other)</code></dt>
<dd>Implements multiplication with assignment.</dd>
<dt><code>__ifloordiv__(self, other)</code></dt>
<dd>Implements integer division with assignment using the <code>//=</code> operator.</dd>
<dt><code>__idiv__(self, other)</code></dt>
<dd>Implements division with assignment using the <code>/=</code> operator.</dd>
<dt><code>__itruediv__(self, other)</code></dt>
<dd>Implements <em>true</em> division with assignment. Note that this only works when <code>from __future__ import division</code> is in effect.</dd>
<dt><code>__imod__(self, other)</code></dt>
<dd>Implements modulo with assignment using the <code>%=</code> operator.</dd>
<dt><code>__ipow__</code></dt>
<dd>Implements behavior for exponents with assignment using the <code>**=</code> operator.</dd>
<dt><code>__ilshift__(self, other)</code></dt>
<dd>Implements left bitwise shift with assignment using the <code><<=</code> operator.</dd>
<dt><code>__irshift__(self, other)</code></dt>
<dd>Implements right bitwise shift with assignment using the <code>>>=</code> operator.</dd>
<dt><code>__iand__(self, other)</code></dt>
<dd>Implements bitwise and with assignment using the <code>&=</code> operator.</dd>
<dt><code>__ior__(self, other)</code></dt>
<dd>Implements bitwise or with assignment using the <code>|=</code> operator.</dd>
<dt><code>__ixor__(self, other)</code></dt>
<dd>Implements bitwise xor with assignment using the <code>^=</code> operator.</dd>
</dl>
<h4>Type conversion magic methods</h4>
<p>Python also has an array of magic methods designed to implement behavior for built in type conversion functions like <code>float()</code>. Here they are:</p>
<dl>
<dt><code>__int__(self)</code></dt>
<dd>Implements type conversion to int.</dd>
<dt><code>__long__(self)</code></dt>
<dd>Implements type conversion to long.</dd>
<dt><code>__float__(self)</code></dt>
<dd>Implements type conversion to float.</dd>
<dt><code>__complex__(self)</code></dt>
<dd>Implements type conversion to complex.</dd>
<dt><code>__oct__(self)</code></dt>
<dd>Implements type conversion to octal.</dd>
<dt><code>__hex__(self)</code></dt>
<dd>Implements type conversion to hexadecimal.</dd>
<dt><code>__index__(self)</code></dt>
<dd>Implements type conversion to an int when the object is used in a slice expression. If you define a custom numeric type that might be used in slicing, you should define <code>__index__</code>.</dd>
<dt><code>__trunc__(self)</code></dt>
<dd>Called when <code>math.trunc(self)</code> is called. <code>__trunc__</code> should return the value of `self truncated to an integral type (usually a long).</dd>
<dt><code>__coerce__(self, other)</code></dt>
<dd>Method to implement mixed mode arithmetic. <code>__coerce__</code> should return <code>None</code> if type conversion is impossible. Otherwise, it should return a pair (2-tuple) of <code>self</code> and <code>other</code>, manipulated to have the same type.</dd>
</dl>
<h2><a id="representations" href="#representations">Representing your Classes</a></h2>
<p>It's often useful to have a string representation of a class. In Python, there are a few methods that you can implement in your class definition to customize how built in functions that return representations of your class behave.</p>
<dl>
<dt><code>__str__(self)</code></dt>
<dd>Defines behavior for when <code>str()</code> is called on an instance of your class.</dd>
<dt><code>__repr__(self)</code></dt>
<dd>Defines behavior for when <code>repr()</code> is called on an instance of your class. The major difference between <code>str()</code> and <code>repr()</code> is intended audience. <code>repr()</code> is intended to produce output that is mostly machine-readable (in many cases, it could be valid Python code even), whereas <code>str()</code> is intended to be human-readable.</dd>
<dt><code>__unicode__(self)</code></dt>
<dd>Defines behavior for when <code>unicode()</code> is called on an instance of your class. <code>unicode()</code> is like <code>str()</code>, but it returns a unicode string. Be wary: if a client calls <code>str()</code> on an instance of your class and you've only defined <code>__unicode__()</code>, it won't work. You should always try to define <code>__str__()</code> as well in case someone doesn't have the luxury of using unicode.</dd>
<dt><code>__format__(self, formatstr)</code></dt>
<dd>Defines behavior for when an instance of your class is used in new-style string formatting. For instance, <code>"Hello, {0:abc}!".format(a)</code> would lead to the call <code>a.__format__("abc")</code>. This can be useful for defining your own numerical or string types that you might like to give special formatting options.</dd>
<dt><code>__hash__(self)</code></dt>
<dd>Defines behavior for when <code>hash()</code> is called on an instance of your class. It has to return an integer, and its result is used for quick key comparison in dictionaries. Note that this usually entails implementing <code>__eq__</code> as well. Live by the following rule: <code>a == b</code> implies <code>hash(a) == hash(b)</code>.</dd>
<dt><code>__nonzero__(self)</code></dt>
<dd>Defines behavior for when <code>bool()</code> is called on an instance of your class. Should return <code>True</code> or <code>False</code>, depending on whether you would want to consider the instance to be <code>True</code> or <code>False</code>.</dd>
<dt><code>__dir__(self)</code></dt>
<dd>Defines behavior for when <code>dir()</code> is called on an instance of your class. This method should return a list of attributes for the user. Typically, implementing <code>__dir__</code> is unnecessary, but it can be vitally important for interactive use of your classes if you redefine <code>__getattr__</code> or <code>__getattribute__</code> (which you will see in the next section) or are otherwise dynamically generating attributes.</dd>
<dt><code>__sizeof__(self)</code></dt>
<dd>Defines behavior for when <code>sys.getsizeof()</code> is called on an instance of your class. This should return the size of your object, in bytes. This is generally more useful for Python classes implemented in C extensions, but it helps to be aware of it.</dd>
</dl>
<p>We're pretty much done with the boring (and example-free) part of the magic methods guide. Now that we've covered some of the more basic magic methods, it's time to move to more advanced material.</p>
<h2><a id="access" href="#access">Controlling Attribute Access</a></h2>
<p>Many people coming to Python from other languages complain that it lacks true encapsulation for classes; that is, there's no way to define private attributes with public getter and setters. This couldn't be farther than the truth: it just happens that Python accomplishes a great deal of encapsulation through "magic", instead of explicit modifiers for methods or fields. Take a look:</p>
<dl>
<dt><code>__getattr__(self, name)</code></dt>
<dd>You can define behavior for when a user attempts to access an attribute that doesn't exist (either at all or yet). This can be useful for catching and redirecting common misspellings, giving warnings about using deprecated attributes (you can still choose to compute and return that attribute, if you wish), or deftly handing an <code>AttributeError</code>. It only gets called when a nonexistent attribute is accessed, however, so it isn't a true encapsulation solution.</dd>
<dt><code>__setattr__(self, name, value)</code></dt>
<dd>Unlike <code>__getattr__</code>, <code>__setattr__</code> is an encapsulation solution. It allows you to define behavior for assignment to an attribute regardless of whether or not that attribute exists, meaning you can define custom rules for any changes in the values of attributes. However, you have to be careful with how you use <code>__setattr__</code>, as the example at the end of the list will show.</dd>
<dt><code>__delattr__(self, name)</code></dt>
<dd>This is the exact same as <code>__setattr__</code>, but for deleting attributes instead of setting them. The same precautions need to be taken as with <code>__setattr__</code> as well in order to prevent infinite recursion (calling <code>del self.name</code> in the implementation of <code>__delattr__</code> would cause infinite recursion).</dd>
<dt><code>__getattribute__(self, name)</code></dt>
<dd>After all this, <code>__getattribute__</code> fits in pretty well with its companions <code>__setattr__</code> and <code>__delattr__</code>. However, I don't recommend you use it. <code>__getattribute__</code> can only be used with new-style classes (all classes are new-style in the newest versions of Python, and in older versions you can make a class new-style by subclassing <code>object</code>. It allows you to define rules for whenever an attribute's value is accessed. It suffers from some similar infinite recursion problems as its partners-in-crime (this time you call the base class's <code>__getattribute__</code> method to prevent this). It also mainly obviates the need for <code>__getattr__</code>, which, when <code>__getattribute__</code> is implemented, only gets called if it is called explicitly or an <code>AttributeError</code> is raised. This method can be used (after all, it's your choice), but I don't recommend it because it has a small use case (it's far more rare that we need special behavior to retrieve a value than to assign to it) and because it can be really difficult to implement bug-free.</dd>
</dl>
<p>You can easily cause a problem in your definitions of any of the methods controlling attribute access. Consider this example:</p>
<pre class="codehilite"><code class="language-python">def __setattr__(self, name, value):
self.name = value
# since every time an attribute is assigned, __setattr__() is called, this
# is recursion.
# so this really means self.__setattr__('name', value). Since the method
# keeps calling itself, the recursion goes on forever causing a crash
def __setattr__(self, name, value):
self.__dict__[name] = value # assigning to the dict of names in the class
# define custom behavior here</code></pre>
<p>Again, Python's magic methods are incredibly powerful, and with great power comes great responsibility. It's important to know the proper way to use magic methods so you don't break any code.</p>
<p>So, what have we learned about custom attribute access in Python? It's not to be used lightly. In fact, it tends to be excessively powerful and counter-intuitive. But the reason why it exists is to scratch a certain itch: Python doesn't seek to make bad things impossible, but just to make them difficult. Freedom is paramount, so you can really do whatever you want. Here's an example of some of the special attribute access methods in action (note that we use <code>super</code> because not all classes have an attribute <code>__dict__</code>):</p>
<pre class="codehilite"><code class="language-python">class AccessCounter(object):
'''A class that contains a value and implements an access counter.
The counter increments each time the value is changed.'''
def __init__(self, val):
super(AccessCounter, self).__setattr__('counter', 0)
super(AccessCounter, self).__setattr__('value', val)
def __setattr__(self, name, value):
if name == 'value':
super(AccessCounter, self).__setattr__('counter', self.counter + 1)
# Make this unconditional.
# If you want to prevent other attributes to be set, raise AttributeError(name)
super(AccessCounter, self).__setattr__(name, value)
def __delattr__(self, name):
if name == 'value':
super(AccessCounter, self).__setattr__('counter', self.counter + 1)
super(AccessCounter, self).__delattr__(name)</code></pre>
<h2><a id="sequence" href="#sequence">Making Custom Sequences</a></h2>
<p>There's a number of ways to get your Python classes to act like built in sequences (<code>dict</code>, <code>tuple</code>, <code>list</code>, <code>str</code>, etc.). These are by far my favorite magic methods in Python because of the absurd degree of control they give you and the way that they magically make a whole array of global functions work beautifully on instances of your class. But before we get down to the good stuff, a quick word on requirements.</p>
<h4>Requirements</h4>
<p>Now that we're talking about creating your own sequences in Python, it's time to talk about <em>protocols</em>. Protocols are somewhat similar to interfaces in other languages in that they give you a set of methods you must define. However, in Python protocols are totally informal and require no explicit declarations to implement. Rather, they're more like guidelines.</p>
<p>Why are we talking about protocols now? Because implementing custom container types in Python involves using some of these protocols. First, there's the protocol for defining immutable containers: to make an immutable container, you need only define <code>__len__</code> and <code>__getitem__</code> (more on these later). The mutable container protocol requires everything that immutable containers require plus <code>__setitem__</code> and <code>__delitem__</code>. Lastly, if you want your object to be iterable, you'll have to define <code>__iter__</code>, which returns an iterator. That iterator must conform to an iterator protocol, which requires iterators to have methods called <code>__iter__</code>(returning itself) and <code>next</code>.</p>
<h4>The magic behind containers</h4>
<p>Without any more wait, here are the magic methods that containers use:</p>
<dl>
<dt><code>__len__(self)</code></dt>
<dd>Returns the length of the container. Part of the protocol for both immutable and mutable containers.</dd>
<dt><code>__getitem__(self, key)</code></dt>
<dd>Defines behavior for when an item is accessed, using the notation <code>self[key]</code>. This is also part of both the mutable and immutable container protocols. It should also raise appropriate exceptions: <code>TypeError</code> if the type of the key is wrong and <code>KeyError</code> if there is no corresponding value for the key.</dd>
<dt><code>__setitem__(self, key, value)</code></dt>
<dd>Defines behavior for when an item is assigned to, using the notation <code>self[nkey] = value</code>. This is part of the mutable container protocol. Again, you should raise <code>KeyError</code> and <code>TypeError</code> where appropriate.</dd>
<dt><code>__delitem__(self, key)</code></dt>
<dd>Defines behavior for when an item is deleted (e.g. <code>del self[key]</code>). This is only part of the mutable container protocol. You must raise the appropriate exceptions when an invalid key is used.</dd>
<dt><code>__iter__(self)</code></dt>
<dd>Should return an iterator for the container. Iterators are returned in a number of contexts, most notably by the <code>iter()</code> built in function and when a container is looped over using the form <code>for x in container:</code>. Iterators are their own objects, and they also must define an <code>__iter__</code> method that returns <code>self</code>.</dd>
<dt><code>__reversed__(self)</code></dt>
<dd>Called to implement behavior for the <code>reversed()</code> built in function. Should return a reversed version of the sequence. Implement this only if the sequence class is ordered, like list or tuple.</dd>
<dt><code>__contains__(self, item)</code></dt>
<dd><code>__contains__</code> defines behavior for membership tests using <code>in</code> and <code>not in</code>. Why isn't this part of a sequence protocol, you ask? Because when <code>__contains__</code> isn't defined, Python just iterates over the sequence and returns <code>True</code> if it comes across the item it's looking for.</dd>
<dt><code>__missing__(self, key)</code></dt>
<dd><code>__missing__</code> is used in subclasses of <code>dict</code>. It defines behavior for whenever a key is accessed that does not exist in a dictionary (so, for instance, if I had a dictionary <code>d</code> and said <code>d["george"]</code> when <code>"george"</code> is not a key in the dict, <code>d.__missing__("george")</code> would be called).</dd>
</dl>
<h4>An example</h4>
<p>For our example, let's look at a list that implements some functional constructs that you might be used to from other languages (Haskell, for example).</p>
<pre class="codehilite"><code class="language-python">class FunctionalList:
'''A class wrapping a list with some extra functional magic, like head,
tail, init, last, drop, and take.'''
def __init__(self, values=None):
if values is None:
self.values = []
else:
self.values = values
def __len__(self):
return len(self.values)
def __getitem__(self, key):
# if key is of invalid type or value, the list values will raise the error
return self.values[key]
def __setitem__(self, key, value):
self.values[key] = value
def __delitem__(self, key):
del self.values[key]
def __iter__(self):
return iter(self.values)
def __reversed__(self):
return reversed(self.values)
def append(self, value):
self.values.append(value)
def head(self):
# get the first element
return self.values[0]
def tail(self):
# get all elements after the first
return self.values[1:]
def init(self):
# get elements up to the last
return self.values[:-1]
def last(self):
# get last element
return self.values[-1]
def drop(self, n):
# get all elements except first n
return self.values[n:]
def take(self, n):
# get first n elements
return self.values[:n]</code></pre>
<p>There you have it, a (marginally) useful example of how to implement your own sequence. Of course, there are more useful applications of custom sequences, but quite a few of them are already implemented in the standard library (batteries included, right?), like <code>Counter</code>, <code>OrderedDict</code>, and <code>NamedTuple</code>.</p>
<h2><a id="reflection" href="#reflection">Reflection</a></h2>
<p>You can also control how reflection using the built in functions <code>isinstance()</code> and <code>issubclass()</code>behaves by defining magic methods. The magic methods are:</p>
<dl>
<dt><code>__instancecheck__(self, instance)</code></dt>
<dd>Checks if an instance is an instance of the class you defined (e.g. <code>isinstance(instance, class)</code>.</dd>
<dt><code>__subclasscheck__(self, subclass)</code></dt>
<dd>Checks if a class subclasses the class you defined (e.g. <code>issubclass(subclass, class)</code>).</dd>
</dl>
<p>The use case for these magic methods might seem small, and that may very well be true. I won't spend too much more time on reflection magic methods because they aren't very important, but they reflect something important about object-oriented programming in Python and Python in general: there is almost always an easy way to do something, even if it's rarely necessary. These magic methods might not seem useful, but if you ever need them you'll be glad that they're there (and that you read this guide!).</p>
<h2><a id="callable" href="#callable">Callable Objects</a></h2>
<p>As you may already know, in Python, functions are first-class objects. This means that they can be passed to functions and methods just as if they were objects of any other kind. This is an incredibly powerful feature.</p>
<p>A special magic method in Python allows instances of your classes to behave as if they were functions, so that you can "call" them, pass them to functions that take functions as arguments, and so on. This is another powerful convenience feature that makes programming in Python that much sweeter.</p>
<dl>
<dt><code>__call__(self, [args...])</code></dt>
<dd>Allows an instance of a class to be called as a function. Essentially, this means that <code>x()</code> is the same as <code>x.__call__()</code>. Note that <code>__call__</code> takes a variable number of arguments; this means that you define <code>__call__</code> as you would any other function, taking however many arguments you'd like it to.</dd>
</dl>
<p><code>__call__</code> can be particularly useful in classes with instances that need to often change state. "Calling" the instance can be an intuitive and elegant way to change the object's state. An example might be a class representing an entity's position on a plane:</p>
<pre class="codehilite"><code class="language-python">class Entity:
'''Class to represent an entity. Callable to update the entity's position.'''
def __init__(self, size, x, y):
self.x, self.y = x, y
self.size = size
def __call__(self, x, y):
'''Change the position of the entity.'''
self.x, self.y = x, y
# snip...</code></pre>
<h2><a id="context" href="#context">Context Managers</a></h2>
<p>In Python 2.5, a new keyword was introduced in Python along with a new method for code reuse: the <code>with</code> statement. The concept of context managers was hardly new in Python (it was implemented before as a part of the library), but not until <a href="http://www.python.org/dev/peps/pep-0343/">PEP 343</a> was accepted did it achieve status as a first-class language construct. You may have seen <code>with</code> statements before:</p>
<pre class="codehilite"><code class="language-python">with open('foo.txt') as bar:
# perform some action with bar</code></pre>
<p>Context managers allow setup and cleanup actions to be taken for objects when their creation is wrapped with a <code>with</code> statement. The behavior of the context manager is determined by two magic methods:</p>
<dl>
<dt><code>__enter__(self)</code></dt>
<dd>Defines what the context manager should do at the beginning of the block created by the <code>with</code> statement. Note that the return value of <code>__enter__</code> is bound to the <em>target</em> of the <code>with</code> statement, or the name after the <code>as</code>.</dd>
<dt><code>__exit__(self, exception_type, exception_value, traceback)</code></dt>
<dd>Defines what the context manager should do after its block has been executed (or terminates). It can be used to handle exceptions, perform cleanup, or do something always done immediately after the action in the block. If the block executes successfully, <code>exception_type</code>, <code>exception_value</code>, and <code>traceback</code> will be <code>None</code>. Otherwise, you can choose to handle the exception or let the user handle it; if you want to handle it, make sure <code>__exit__</code> returns <code>True</code> after all is said and done. If you don't want the exception to be handled by the context manager, just let it happen.</dd>
</dl>
<p><code>__enter__</code> and <code>__exit__</code> can be useful for specific classes that have well-defined and common behavior for setup and cleanup. You can also use these methods to create generic context managers that wrap other objects. Here's an example:</p>
<pre class="codehilite"><code class="language-python">class Closer:
'''A context manager to automatically close an object with a close method
in a with statement.'''
def __init__(self, obj):
self.obj = obj
def __enter__(self):
return self.obj # bound to target
def __exit__(self, exception_type, exception_val, trace):
try:
self.obj.close()
except AttributeError: # obj isn't closable
print 'Not closable.'
return True # exception handled successfully</code></pre>
<p>Here's an example of <code>Closer</code> in action, using an FTP connection to demonstrate it (a closable socket):</p>
<pre class="codehilite"><code class="language-pythonconsole">>>> from magicmethods import Closer
>>> from ftplib import FTP
>>> with Closer(FTP('ftp.somesite.com')) as conn:
... conn.dir()
...
# output omitted for brevity
>>> conn.dir()
# long AttributeError message, can't use a connection that's closed
>>> with Closer(int(5)) as i:
... i += 1
...
Not closable.
>>> i
6</code></pre>
<p>See how our wrapper gracefully handled both proper and improper uses? That's the power of context managers and magic methods. Note that the Python standard library includes a module <a href="http://docs.python.org/library/contextlib.html">contextlib</a> that contains a context manager, <code>contextlib.closing()</code>, that does approximately the same thing (without any handling of the case where an object does not have a <code>close()</code> method).</p>
<h2><a id="abcs" href="#abcs">Abstract Base Classes</a></h2>
<p>See http://docs.python.org/2/library/abc.html.</p>
<h2><a id="descriptor" href="#descriptor">Building Descriptor Objects</a></h2>
<p>Descriptors are classes which, when accessed through either getting, setting, or deleting, can also alter other objects. Descriptors aren't meant to stand alone; rather, they're meant to be held by an owner class. Descriptors can be useful when building object-oriented databases or classes that have attributes whose values are dependent on each other. Descriptors are particularly useful when representing attributes in several different units of measurement or representing computed attributes (like distance from the origin in a class to represent a point on a grid).</p>
<p>To be a descriptor, a class must have at least one of <code>__get__</code>, <code>__set__</code>, and <code>__delete__</code> implemented. Let's take a look at those magic methods:</p>
<dl>
<dt><code>__get__(self, instance, owner)</code></dt>
<dd>Define behavior for when the descriptor's value is retrieved. <code>instance</code> is the instance of the owner object. <code>owner</code> is the owner class itself.</dd>
<dt><code>__set__(self, instance, value)</code></dt>
<dd>Define behavior for when the descriptor's value is changed. <code>instance</code> is the instance of the owner class and <code>value</code> is the value to set the descriptor to.</dd>
<dt><code>__delete__(self, instance)</code></dt>
<dd>Define behavior for when the descriptor's value is deleted. <code>instance</code> is the instance of the owner object.</dd>
</dl>
<p>Now, an example of a useful application of descriptors: unit conversions.</p>
<pre class="codehilite"><code class="language-python">class Meter(object):
'''Descriptor for a meter.'''
def __init__(self, value=0.0):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = float(value)
class Foot(object):
'''Descriptor for a foot.'''
def __get__(self, instance, owner):
return instance.meter * 3.2808
def __set__(self, instance, value):
instance.meter = float(value) / 3.2808
class Distance(object):
'''Class to represent distance holding two descriptors for feet and
meters.'''
meter = Meter()
foot = Foot()</code></pre>
<h2><a id="copying" href="#copying">Copying</a></h2>
<p>Sometimes, particularly when dealing with mutable objects, you want to be able to copy an object and make changes without affecting what you copied from. This is where Python's <a href="http://docs.python.org/library/copy.html"><code>copy</code></a> comes into play. However (fortunately), Python modules are not sentient, so we don't have to worry about a Linux-based robot uprising, but we do have to tell Python how to efficiently copy things.</p>
<dl>
<dt><code>__copy__(self)</code></dt>
<dd>Defines behavior for <code>copy.copy()</code> for instances of your class. <code>copy.copy()</code> returns a <em>shallow copy</em> of your object -- this means that, while the instance itself is a new instance, all of its data is referenced -- i.e., the object itself is copied, but its data is still referenced (and hence changes to data in a shallow copy may cause changes in the original).</dd>
<dt><code>__deepcopy__(self, memodict={})</code></dt>
<dd>Defines behavior for <code>copy.deepcopy()</code> for instances of your class. <code>copy.deepcopy()</code> returns a <em>deep copy</em> of your object -- the object <em>and</em> its data are both copied. <code>memodict</code> is a cache of previously copied objects -- this optimizes copying and prevents infinite recursion when copying recursive data structures. When you want to deep copy an individual attribute, call <code>copy.deepcopy()</code> on that attribute with <code>memodict</code> as the first argument.</dd>
</dl>
<p>What are some use cases for these magic methods? As always, in any case where you need more fine-grained control than what the default behavior gives you. For instance, if you are attempting to copy an object that stores a cache as a dictionary (which might be large), it might not make sense to copy the cache as well -- if the cache can be shared in memory between instances, then it should be.</p>
<h2><a id="pickling" href="#pickling">Pickling Your Objects</a></h2>
<p>If you spend time with other Pythonistas, chances are you've at least heard of pickling. Pickling is a serialization process for Python data structures, and can be incredibly useful when you need to store an object and retrieve it later (usually for caching). It's also a major source of worries and confusion.</p>
<p>Pickling is so important that it doesn't just have its own module (<code>pickle</code>), but its own <em>protocol</em> and the magic methods to go with it. But first, a brief word on how to pickle existing types(feel free to skip it if you already know).</p>
<h3>Pickling: A Quick Soak in the Brine</h3>
<p>Let's dive into pickling. Say you have a dictionary that you want to store and retrieve later. You couldwrite it's contents to a file, carefully making sure that you write correct syntax, then retrieve it using either <code>exec()</code> or processing the file input. But this is precarious at best: if you store important data in plain text, it could be corrupted or changed in any number of ways to make your program crash or worse run malicious code on your computer. Instead, we're going to pickle it:</p>
<pre class="codehilite"><code class="language-python">import pickle
data = {'foo': [1, 2, 3],
'bar': ('Hello', 'world!'),
'baz': True}
jar = open('data.pkl', 'wb')
pickle.dump(data, jar) # write the pickled data to the file jar
jar.close()</code></pre>
<p>Now, a few hours later, we want it back. All we have to do is unpickle it:</p>
<pre class="codehilite"><code class="language-python">import pickle
pkl_file = open('data.pkl', 'rb') # connect to the pickled data
data = pickle.load(pkl_file) # load it into a variable
print data
pkl_file.close()</code></pre>
<p>What happens? Exactly what you expect. It's just like we had <code>data</code> all along.</p>
<p>Now, for a word of caution: pickling is not perfect. Pickle files are easily corrupted on accident and on purpose. Pickling may be more secure than using flat text files, but it still can be used to run malicious code. It's also incompatible across different versions of Python, so don't expect to distribute pickled objects and expect people to be able to open them. However, it can also be a powerful tool for caching and other common serialization tasks.</p>
<h3>Pickling your own Objects</h3>
<p>Pickling isn't just for built-in types. It's for any class that follows the pickle protocol. The pickle protocol has four optional methods for Python objects to customize how they act (it's a bit different for C extensions, but that's not in our scope):</p>
<dl>
<dt><code>__getinitargs__(self)</code></dt>
<dd>If you'd like for <code>__init__</code> to be called when your class is unpickled, you can define <code>__getinitargs__</code>, which should return a tuple of the arguments that you'd like to be passed to <code>__init__</code>. Note that this method will only work for old-style classes.</dd>
<dt><code>__getnewargs__(self)</code></dt>
<dd>For new-style classes, you can influence what arguments get passed to <code>__new__</code> upon unpickling. This method should also return a tuple of arguments that will then be passed to <code>__new__</code>.</dd>
<dt><code>__getstate__(self)</code></dt>
<dd>Instead of the object's <code>__dict__</code> attribute being stored, you can return a custom state to be stored when the object is pickled. That state will be used by <code>__setstate__</code> when the object is unpickled.</dd>
<dt><code>__setstate__(self, state)</code></dt>
<dd>When the object is unpickled, if <code>__setstate__</code> is defined the object's state will be passed to it instead of directly applied to the object's <code>__dict__</code>. This goes hand in hand with <code>__getstate__</code>: when both are defined, you can represent the object's pickled state however you want with whatever you want.</dd>
<dt><code>__reduce__(self)</code></dt>
<dd>When defining extension types (i.e., types implemented using Python's C API), you have to tell Python how to pickle them if you want them to pickle them. <code>__reduce__()</code> is called when an object defining it is pickled. It can either return a string representing a global name that Python will look up and pickle, or a tuple. The tuple contains between 2 and 5 elements: a callable object that is called to recreate the object, a tuple of arguments for that callable object, state to be passed to <code>__setstate__</code> (optional), an iterator yielding list items to be pickled (optional), and an iterator yielding dictionary items to be pickled (optional).</dd>
<dt><code>__reduce_ex__(self)</code></dt>
<dd><code>__reduce_ex__</code> exists for compatibility. If it is defined, <code>__reduce_ex__</code> will be called over <code>__reduce__</code> on pickling. <code>__reduce__</code> can be defined as well for older versions of the pickling API that did not support <code>__reduce_ex__</code>.</dd>
</dl>
<h3>An Example</h3>
<p>Our example is a <code>Slate</code>, which remembers what its values have been and when those values were written to it. However, this particular slate goes blank each time it is pickled: the current value will not be saved.</p>
<pre class="codehilite"><code class="language-python">import time
class Slate:
'''Class to store a string and a changelog, and forget its value when
pickled.'''
def __init__(self, value):
self.value = value
self.last_change = time.asctime()
self.history = {}
def change(self, new_value):
# Change the value. Commit last value to history
self.history[self.last_change] = self.value
self.value = new_value
self.last_change = time.asctime()
def print_changes(self):
print 'Changelog for Slate object:'
for k, v in self.history.items():
print '%s\t %s' % (k, v)
def __getstate__(self):
# Deliberately do not return self.value or self.last_change.
# We want to have a "blank slate" when we unpickle.
return self.history
def __setstate__(self, state):
# Make self.history = state and last_change and value undefined
self.history = state
self.value, self.last_change = None, None</code></pre>
<h2><a id="conclusion" href="#conclusion">Conclusion</a></h2>
<p>The goal of this guide is to bring something to anyone that reads it, regardless of their experience with Python or object-oriented programming. If you're just getting started with Python, you've gained valuable knowledge of the basics of writing feature-rich, elegant, and easy-to-use classes. If you're an intermediate Python programmer, you've probably picked up some slick new concepts and strategies and some good ways to reduce the amount of code written by you and clients. If you're an expert Pythonista, you've been refreshed on some of the stuff you might have forgotten about and maybe picked up a few new tricks along the way. Whatever your experience level, I hope that this trip through Python's special methods has been truly magical. (I couldn't resist the final pun!)</p><h2><a id="appendix1" href="#appendix1">Appendix 1: How to Call Magic Methods</a></h2>
<p>Some of the magic methods in Python directly map to built-in functions; in this case, how to invoke them is fairly obvious. However, in other
cases, the invocation is far less obvious. This appendix is devoted to exposing non-obvious syntax that leads to magic methods getting called.</p>
<table>
<thead>
<tr>
<th>Magic Method</th>
<th>When it gets invoked (example)</th>
<th>Explanation</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>__new__(cls [,...])</code></td>
<td><code>instance = MyClass(arg1, arg2)</code></td>
<td><code>__new__</code> is called on instance creation</td>
</tr>
<tr>
<td><code>__init__(self [,...])</code></td>
<td><code>instance = MyClass(arg1, arg2)</code></td>
<td><code>__init__</code> is called on instance creation</td>
</tr>
<tr>
<td><code>__cmp__(self, other)</code></td>
<td><code>self == other</code>, <code>self > other</code>, etc.</td>
<td>Called for any comparison</td>
</tr>
<tr>
<td><code>__pos__(self)</code></td>
<td><code>+self</code></td>
<td>Unary plus sign</td>
</tr>
<tr>
<td><code>__neg__(self)</code></td>
<td><code>-self</code></td>
<td>Unary minus sign</td>
</tr>
<tr>
<td><code>__invert__(self)</code></td>
<td><code>~self</code></td>
<td>Bitwise inversion</td>
</tr>
<tr>
<td><code>__index__(self)</code></td>
<td><code>x[self]</code></td>
<td>Conversion when object is used as index</td>
</tr>
<tr>
<td><code>__nonzero__(self)</code></td>
<td><code>bool(self)</code></td>
<td>Boolean value of the object</td>
</tr>
<tr>
<td><code>__getattr__(self, name)</code></td>
<td><code>self.name # name doesn't exist</code></td>
<td>Accessing nonexistent attribute</td>
</tr>
<tr>
<td><code>__setattr__(self, name, val)</code></td>
<td><code>self.name = val</code></td>
<td>Assigning to an attribute</td>
</tr>
<tr>
<td><code>__delattr__(self, name)</code></td>
<td><code>del self.name</code></td>
<td>Deleting an attribute</td>
</tr>
<tr>
<td><code>__getattribute__(self, name)</code></td>
<td><code>self.name</code></td>
<td>Accessing any attribute</td>
</tr>
<tr>
<td><code>__getitem__(self, key)</code></td>
<td><code>self[key]</code></td>
<td>Accessing an item using an index</td>
</tr>
<tr>
<td><code>__setitem__(self, key, val)</code></td>
<td><code>self[key] = val</code></td>
<td>Assigning to an item using an index</td>
</tr>
<tr>
<td><code>__delitem__(self, key)</code></td>
<td><code>del self[key]</code></td>
<td>Deleting an item using an index</td>
</tr>
<tr>
<td><code>__iter__(self)</code></td>
<td><code>for x in self</code></td>
<td>Iteration</td>
</tr>
<tr>
<td><code>__contains__(self, value)</code></td>
<td><code>value in self</code>, <code>value not in self</code></td>
<td>Membership tests using <code>in</code></td>
</tr>
<tr>
<td><code>__call__(self [,...])</code></td>
<td><code>self(args)</code></td>
<td>"Calling" an instance</td>
</tr>
<tr>
<td><code>__enter__(self)</code></td>
<td><code>with self as x:</code></td>
<td><code>with</code> statement context managers</td>
</tr>
<tr>
<td><code>__exit__(self, exc, val, trace)</code></td>
<td><code>with self as x:</code></td>
<td><code>with</code> statement context managers</td>
</tr>
<tr>
<td><code>__getstate__(self)</code></td>
<td><code>pickle.dump(pkl_file, self)</code></td>
<td>Pickling</td>
</tr>
<tr>
<td><code>__setstate__(self)</code></td>
<td><code>data = pickle.load(pkl_file)</code></td>
<td>Pickling</td>
</tr>
</tbody>
</table>
<p>Hopefully, this table should have cleared up any questions you might have had about what syntax invokes which magic method.</p>
<h2><a id="appendix2" href="#appendix2">Appendix 2: Changes in Python 3</a></h2>
<p>Here, we document a few major places where Python 3 differs from 2.x in terms of its object model:</p>
<ul>
<li>Since the distinction between string and unicode has been done away with in Python 3, <code>__unicode__</code> is gone and <code>__bytes__</code> (which behaves similarly to <code>__str__</code> and <code>__unicode__</code> in 2.7) exists for a new built-in for constructing byte arrays.</li>
<li>Since division defaults to true division in Python 3, <code>__div__</code> is gone in Python 3</li>
<li><code>__coerce__</code> is gone due to redundancy with other magic methods and confusing behavior</li>
<li><code>__cmp__</code> is gone due to redundancy with other magic methods</li>
<li><code>__nonzero__</code> has been renamed to <code>__bool__</code></li>
</ul><script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18615621-3']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>