GithubHelp home page GithubHelp logo

josxa / python-chain Goto Github PK

View Code? Open in Web Editor NEW

This project forked from quintoandar/python-chain

0.0 1.0 0.0 40 KB

An easy to use function chaining pattern on Python.

License: MIT License

Makefile 1.93% Python 91.35% Gherkin 6.71%

python-chain's Introduction


Python Chain Logo

An easy to use function chaining pattern on Python.

๐Ÿ“– About this Project

Chaining functions is a common functional development pattern that is pretty difficult on Python. Usually, we need to pass some data through a pipeline, process or series of functions in order to get a specific output. Without this lib, you would need to wrap those functions on a class or assign each result on a variable.

With python-chain you can create an initial state and execute a chain of functions, nourishing that state during the pipeline, like this:

Code sample

๐Ÿค– Getting Started

On this section, you'll learn all the prerequisites and basic knowledge in order to use this library on your projects.

Installation

You can install it using pip, running:

pip install python-chain

Common Usage

Creating Chainable Functions

You can chain functions by decorating them with the @chain decorator. Like the following:

import chain


@chain
def some_pretty_func(state):
  ...

# Now you can chain that function with the operator>>

Using State

Every chain has a state. That state is an Object with immutable attributes. The current Chain state will be passed automatically on the keyword argument context. Every chain should start with a given state, even if it empty. You can create a new one by using:

import chain

state = chain.state()

If you want to feed data into your initial state, you can pass then as kwargs. The key-value pair on the kwargs of your state will be passed as attributes on your chain context. Like so:

import chain

state = chain.state(foo='bar')

@chain
def test_chain(context):
  print(context.foo)
  # bar

Using States on Chains

Every mutation that you do in a chain function will add it to the next function. You can merge what you have learned both on states and functions by following:

import chain

@chain
def calculate_average(context, type='meter'):
  nbs = [house.get(type) for house in state.houses]

  context.avg = sum(nbs) / len(nbs)

@chain
def add_houses(context):
  houses = [
    { meter: 3, },
    { meter: 10, },
  ]

  context.houses = houses

result = chain.state() >> add_houses >> calculate_average
print(result.current)
#
# {
#   avg: 6.5,
#   houses: [
#     { meter: 3 },
#     { meter: 10 },
#   ]
# }
#

If you don't return anything on your final chain function it will automatically return the Context object. They have a lot of properties, and one of them is the current attribute. That will return the current state of your given context.

Finishing a Chain

Every time a chain is finished, it will automatically return its context. You can also add an output by retuning the data that you want on the last step of the chain, like this:

import chain

@chain
def get_name(context):
  return context.name

@chain
def add_user(context):
  context.name = 'foo'

result = chain.state() >> add_user >> get_name
print(result.output)
#
# 'foo'
#

Passing arguments directly

You can pass any args or kwargs directly to the next function. They should be passed returning a tuple with all the args on the first argument and the kwargs on the second. You can do so like this:

import chain

@chain
def store_result(result, context, type=None):
  context.result = result
  context.type = type

@chain
def add_result(context):
  args = ('foo',)
  kwargs = {type: 'bar'}

  return args, kwargs

result = chain.state() >> add_result >> store_result
print(result.current)
#
# {
#   result: 'foo',
#   type: 'bar',
# }
#

Be careful. This would create a strong dependency between those two functions. Chain will always pass the args and kwargs that you've created and it will break the chain if the next function doesn't accept those params. Also, always set a state params, because it will be passed by the Chain with the current state.

โœ๏ธ Contributing

Contributions are what makes the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated. You can learn how to contribute to this project on the CONTRIBUTING file.

๐Ÿ”“ License

Distributed under the MIT License. See LICENSE for more information.

python-chain's People

Contributors

allrod5 avatar lucianohgo avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.