Skip to content

Recipes #4

Description

@mentalisttraceur

Moving the recipes from the README into here for now:

  • If you want composing zero functions to be the identity function:

    from functools import partial
    
    def identity(x):
        return x
    
    icompose = partial(compose, identity)
  • To compose arguments in reverse order:

     def rcompose(*functions):
          return compose(*reversed(functions))
  • When you need composition to produce a normal function, for example on Python implementations which don't implement the descriptor protocol:

    def fcompose(*functions):
        composed = compose(*functions)
        return lambda *args, **kwargs: composed.__call__(*args, **kwargs)

    (The explicit .__call__ makes this recipe work even on Python implementations that don't support overloading the function call operator.)

  • Composition as a decorator, so that you can use @composed_with(f) on top of def g(...) to get the same result as g = compose(f, g).

    from functools import partial
    
    composed_with = partial(partial, sacompose)

    (Using sacompose allows this decorator to handle async functions too.)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions