Skip to main content

Collection of lower-level utilities that enhance code compatibility and validation.

Project description

https://github.com/brunonicko/slotted/workflows/MyPy/badge.svg https://github.com/brunonicko/slotted/workflows/Lint/badge.svg https://github.com/brunonicko/slotted/workflows/Tests/badge.svg https://readthedocs.org/projects/slotted/badge/?version=stable https://img.shields.io/github/license/brunonicko/slotted?color=light-green https://static.pepy.tech/personalized-badge/slotted?period=total&units=international_system&left_color=grey&right_color=brightgreen&left_text=Downloads https://img.shields.io/pypi/pyversions/slotted?color=light-green&style=flat

Enforces usage of __slots__ for python classes and provides pickling capabilities.

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'

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

slotted-3.1.0.tar.gz (8.4 kB view hashes)

Uploaded Source

Built Distribution

slotted-3.1.0-py2.py3-none-any.whl (6.7 kB view hashes)

Uploaded Python 2 Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page