Skip to main content

Forwardable as in Ruby's stdlib

Project description

Utility for easy object composition via delegation. Roughly ported from Ruby’s forwardable standard library.

Installation

$ pip install forwardable

Usage

The @forwardable.forwardable() decorator enables you to use def_delegator in a class definition block.

from forwardable import forwardable

@forwardable() # Note the () here, which is required.
class Foo(object):
    def_delegators('bar', ('add', '__len__'))

    def __init__(self)
        self.bar = set()

foo = Foo()
foo.add(1) # Delegates to foo.bar.add()
assert len(foo) == 1

Easy, heh?

In case you only need to delegate one method to a delegatee, just use def_delegator:

from forwardable import forwardable

@forwardable()
class Foo(object):
    def_delegator('bar', '__len__')

    def __init__(self)
        self.bar = set()

assert len(Foo()) == 0

And it should work just fine.

Less Magical Usage

If you hesitate to touch the @forwardable() injection magic, just from forwardable import def_delegator, def_delegators, use them in a class definition and you’ll be fine.

License

MIT license.

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

forwardable-0.2.1.tar.gz (4.1 kB view hashes)

Uploaded Source

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