Skip to main content

Python package facilitating duck typing through attribute traverse utilities

Project description

duckt

Travis CI build status codecov PyPI version

A small Python package facilitating duck typing through attribute traverse utilities

This replaces try/except chains when trying to call different methods:

from duckt import Duck, DuckCall

class Lion:
    def roar(self):
        return "roar!"

creature = Lion()
assert Duck(creature).attr_call(
    DuckCall("make_sound", ["woof"]), # tries to call creature.make_sound("woof")
    DuckCall("make_sound", ["buzz", 100]), # tries to call creature.buzz("buzz", 100)
    DuckCall("bark"), # creature.bark()
    DuckCall("roar"), # creature.roar()
    DuckCall("speak", ["Hello "], {"times": 3}) # creature.speak("Hello ", times=3)
) == "roar!"

 # returns the output of the first successfull call
# if none of the call attempts was successful then the last raised error will be thrown

DuckCall class is fully replacable here with any custom callable accepting single argument. This argument is the Duck-wrapped object, so you can implement custom attribute extracting and/or calling behavior here. AttributeErrors and TypeErrors thrown from this callable is handled by the Duck instance.

Simplified interface for property extraction:

from duckt import Duck

class Person:
    full_name = "John Doe"

some_person = Person()
name = Duck(some_person).attr('first_name', 'name', 'full_name')
# name now is equal to the first present attribute
# otherwise AttributeError is thrown

You may also use Duck as wrapper to a callable:

from duckt import Duck

def foo(some_string):
    print(some_string)

duck = Duck(foo)
duck.call(
    ["hello", "world"], # foo("hello", "world")
    ["hello world"],    # foo("hello world")
    [[], {"hello": "world"}]  # foo(hello="world")
)

Installation

pip install duckt

That's it.

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

duckt-0.1.1.tar.gz (3.6 kB view hashes)

Uploaded Source

Built Distribution

duckt-0.1.1-py3-none-any.whl (3.6 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