Skip to main content

autoslot

Project description

https://img.shields.io/badge/stdlib--only-yes-green.svg https://travis-ci.org/cjrh/autoslot.svg?branch=master https://coveralls.io/repos/github/cjrh/autoslot/badge.svg?branch=master https://img.shields.io/pypi/pyversions/autoslot.svg https://img.shields.io/github/tag/cjrh/autoslot.svg https://img.shields.io/badge/install-pip%20install%20autoslot-ff69b4.svg https://img.shields.io/pypi/v/autoslot.svg https://img.shields.io/badge/calver-YYYY.MM.MINOR-22bfda.svg

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

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.

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


Download files

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

Source Distribution

autoslot-2017.10.3.tar.gz (9.0 kB view hashes)

Uploaded Source

Built Distribution

autoslot-2017.10.3-py3-none-any.whl (16.2 kB view hashes)

Uploaded 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