Skip to content

Commit 4227516

Browse files
disconnect3dDominik Czarnota
authored andcommitted
Better example of __slots__magic.rst
1 parent d1685ed commit 4227516

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

__slots__magic.rst

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ of attributes. Here is an example with and without ``__slots__``:
1919
.. code:: python
2020
2121
class MyClass(object):
22-
def __init__(name, identifier):
22+
def __init__(self, name, identifier):
2323
self.name = name
2424
self.identifier = identifier
2525
self.set_up()
@@ -31,7 +31,7 @@ of attributes. Here is an example with and without ``__slots__``:
3131
3232
class MyClass(object):
3333
__slots__ = ['name', 'identifier']
34-
def __init__(name, identifier):
34+
def __init__(self, name, identifier):
3535
self.name = name
3636
self.identifier = identifier
3737
self.set_up()
@@ -43,3 +43,49 @@ technique.
4343

4444
On a sidenote, you might want to give PyPy a try. It does all of these
4545
optimizations by default.
46+
47+
48+
Below you can see an example showing exact memory usage with and without ``__slots__`` done in IPython thanks to https://github.com/ianozsvald/ipython_memory_usage
49+
50+
.. code:: python
51+
52+
Python 3.4.3 (default, Jun 6 2015, 13:32:34)
53+
Type "copyright", "credits" or "license" for more information.
54+
55+
IPython 4.0.0 -- An enhanced Interactive Python.
56+
? -> Introduction and overview of IPython's features.
57+
%quickref -> Quick reference.
58+
help -> Python's own help system.
59+
object? -> Details about 'object', use 'object??' for extra details.
60+
61+
In [1]: import ipython_memory_usage.ipython_memory_usage as imu
62+
63+
In [2]: imu.start_watching_memory()
64+
In [2] used 0.0000 MiB RAM in 5.31s, peaked 0.00 MiB above current, total RAM usage 15.57 MiB
65+
66+
In [3]: %cat slots.py
67+
class MyClass(object):
68+
__slots__ = ['name', 'identifier']
69+
def __init__(self, name, identifier):
70+
self.name = name
71+
self.identifier = identifier
72+
73+
num = 1024*256
74+
x = [MyClass(1,1) for i in range(num)]
75+
In [3] used 0.2305 MiB RAM in 0.12s, peaked 0.00 MiB above current, total RAM usage 15.80 MiB
76+
77+
In [4]: from slots import *
78+
In [4] used 9.3008 MiB RAM in 0.72s, peaked 0.00 MiB above current, total RAM usage 25.10 MiB
79+
80+
In [5]: %cat noslots.py
81+
class MyClass(object):
82+
def __init__(self, name, identifier):
83+
self.name = name
84+
self.identifier = identifier
85+
86+
num = 1024*256
87+
x = [MyClass(1,1) for i in range(num)]
88+
In [5] used 0.1758 MiB RAM in 0.12s, peaked 0.00 MiB above current, total RAM usage 25.28 MiB
89+
90+
In [6]: from noslots import *
91+
In [6] used 22.6680 MiB RAM in 0.80s, peaked 0.00 MiB above current, total RAM usage 47.95 MiB

0 commit comments

Comments
 (0)