Classes and metaclasses for easier ``__slots__`` handling.
Project description
autoslot
Automatic “__slots__”.
Demo
from autoslot import Slots
class Compact(Slots):
def __init__(self, a, b):
self.x = a
self.y = b
This produces exactly the same class as if you had done:
class Compact:
__slots__ = {'x', 'y'}
def __init__(self, a, b):
self.x = a
self.y = b
Simply: the code inside __init__() is scanned to find all assignments to attributes on self, and these are added as __slots__.
The benefit of using the metaclass version is that you can modify the code inside the __init__() method to add more attributes, and those changes will automatically be reflected in the __slots__ definition.
You can also have the best of both worlds: slots for fields you expect, as well as a __dict__ for those you don’t:
from autoslot import SlotsPlusDict
class SemiCompact(SlotsPlusDict):
def __init__(self, a, b):
self.x = a
self.y = b
inst = SemiCompact(1, 2)
inst.z = 123
Attributes x and y will be stored in slots, while all other dynamically-assigned attributes will go into the usual __dict__ instance inside the class. If most fields are expected, then dictionary bloat will be contained.
How does it work?
See for yourself–the code is embarrassingly small!
In words: the metaclass finds the __init__() method, if present, and accesses its bytecode. It looks for all assignments to attributes of self, and considers those to be desired __slots__ entries. Then the metaclass injects __slots__ into the namespace of the class definition and thereafter allows class creation to proceed as normal.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for autoslot-2017.10.6-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 35abd005dc8fe94c78f3229f8d75454eb7a22c091a00ec6ec5080e77d048b361 |
|
MD5 | 8e91d6a1223ea0e72a1af81f210f5a94 |
|
BLAKE2b-256 | e0e20c2570c30d5b41681df92bb8939385ed83eaabf58d3ddfd1b9adc0348adb |