Enforces usage of '__slots__' for python classes.
Project description
Overview
Enforces usage of __slots__ for Python classes.
Motivation
Besides the performance benefits, using __slots__ also prevents the client code from setting attributes that were not initially defined for instances of classes, which usually happens by mistake especially in environments where static type checking is not being performed.
So forcing it upon a class and its subclasses might be a desirable thing to do for classes that are part of an API, for example.
Examples
When defining a Slotted class with no __slots__ declaration, it assumes it has empty slots, which is equivalent to declaring __slots__ = ().
>>> from slotted import Slotted
>>> class Foo(Slotted):
... pass # implicit declaration of __slots__ = ()
...
>>> foo = Foo()
>>> foo.bar = 1
Traceback (most recent call last):
AttributeError: 'Foo' object has no attribute 'bar'
Slotted classes can be mixed with regular classes as long as they and all of their bases implement __slots__.
>>> from slotted import Slotted
>>> class Bar(object):
... __slots__ = ("bar",)
>>> class Foo(Bar, Slotted):
... __slots__ = ("foo",)
...
>>> foo = Foo()
If any non-Slotted class anywhere in the chain does not implement __slots__, a TypeError exception is raised.
>>> from slotted import Slotted
>>> class Bar(object):
... pass
>>> class Foo(Bar, Slotted):
... __slots__ = ("foo",)
...
Traceback (most recent call last):
TypeError: base 'Bar' is not slotted
Slotted behavior can also be achieved by using the SlottedMeta metaclass.
>>> from six import with_metaclass
>>> from slotted import SlottedMeta
>>> class Foo(with_metaclass(SlottedMeta, object)):
... pass # implicit declaration of __slots__ = ()
...
>>> foo = Foo()
>>> foo.bar = 1
Traceback (most recent call last):
AttributeError: 'Foo' object has no attribute 'bar'
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 slotted-5.0.0-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7ad47ab7e351228783fcb3a0548ea48ddd4178ef425e817fe3aec13bd38c0d6c |
|
MD5 | 54f53203d2f9f331ba232165ae38e72e |
|
BLAKE2b-256 | 5ecb2c9e80a8f9f1ed2eb304c0095f75cdf52721fc773ec1d70859dc2e68790d |