Enforces usage of '__slots__' for python classes.
Project description
Overview
slotted enforces usage of __slots__ for Python classes.
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:
... __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:
... pass
>>> class Foo(Bar, Slotted):
... __slots__ = ("foo",)
...
Traceback (most recent call last):
TypeError: base 'Bar' does not define __slots__
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'
abc
slotted also provides generic versions of the collection.abc classes.
>>> from typing import TypeVar
>>> from slotted import SlottedMapping, SlottedSequence, SlottedSet
>>> KT = TypeVar("KT")
>>> VT = TypeVar("VT")
>>> class MyMapping(SlottedMapping[KT, VT]):
... pass # implicit declaration of __slots__ = ()
...
>>> class MySequence(SlottedSequence[VT]):
... pass # implicit declaration of __slots__ = ()
...
>>> class MySet(SlottedSet[VT]):
... pass # implicit declaration of __slots__ = ()
...
For Python 2.7, slotted adds a SlottedCollection class, even though the original Collection is not available.
>>> from typing import TypeVar
>>> from slotted import SlottedCollection
>>> T = TypeVar("T")
>>> class MyCollection(SlottedCollection[T]):
... pass # implicit declaration of __slots__ = ()
...
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-4.2.1-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | dd35cceca0276b62832b9e9ee7c16b2aeeb9ba1ee0c60194167c9b85dd9b4427 |
|
MD5 | 9e8ee5b2d5dc8ae10b3e3f0ba9daf857 |
|
BLAKE2b-256 | c2819b116fa1d4072bf366243362be519a8b28a9fb7544775eaf0309d5cb10b7 |