Python Slots Inheritance

Python Slots Inheritance 4,3/5 6010 reviews
Python slots inheritance online
  1. Python Inheritance Examples
  2. Python Function Inheritance
  3. Python __slots__ Multiple Inheritance

In Python every class can have instance attributes. By default Pythonuses a dict to store an object’s instance attributes. This is reallyhelpful as it allows setting arbitrary new attributes at runtime.

However, for small classes with known attributes it might be abottleneck. The dict wastes a lot of RAM. Python can’t just allocatea static amount of memory at object creation to store all theattributes. Therefore it sucks a lot of RAM if you create a lot ofobjects (I am talking in thousands and millions). Still there is a wayto circumvent this issue. It involves the usage of __slots__ totell Python not to use a dict, and only allocate space for a fixed setof attributes. Here is an example with and without __slots__:

Python Inheritance Examples

Decorator for adding slots. Python3.7 provides dataclasses module for faster class creation. Unfortunately there's no support for slots. If you want to create more memory efficient instances, you need to do it by yourself or use dataslots.dataslots decorator. Usage Simple example @dataslots @dataclass class Point2D: x: int y: int Inheritance. Continuing our consideration of slots in Python 3, we take a look at issues of inheritance and there's also a really useful pickling tip, with or without.

Without__slots__:

Slots

With__slots__:

Python Function Inheritance

The second piece of code will reduce the burden on your RAM. Some peoplehave seen almost 40 to 50% reduction in RAM usage by using thistechnique.

On a sidenote, you might want to give PyPy a try. It does all of theseoptimizations by default.

Python __slots__ Multiple Inheritance

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