Skip to content

Instantly share code, notes, and snippets.

@outloudvi
Created January 25, 2019 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save outloudvi/897dabdf0cb34953df33565e84cf6f41 to your computer and use it in GitHub Desktop.
Save outloudvi/897dabdf0cb34953df33565e84cf6f41 to your computer and use it in GitHub Desktop.
Python currying helper.
# Author : Outvi V
# License: MIT
class CurryingBase():
"""
This is a class that helps you to do with something called 'currying'.
Initially you need to give it two functions.
One is the final 'firing' function and another is the 'kick' function checking the dependencies.
"""
def __init__(self, fire, kick, *margs, **mkwargs):
self.fire = fire
self.kick = kick
self.args = []
self.kwargs = {}
def __call__(self, *args, **kwargs):
margs = self.args + list(args)
mkwargs = {}
mkwargs.update(self.kwargs)
mkwargs.update(kwargs)
if self.kick(margs, mkwargs):
return self.prepare(self.fire, margs, mkwargs)
return CurryingBase(self.fire, self.kick, *margs, **mkwargs)
def prepare(self, fire, margs, mkwargs):
j = 0
for i in fire.__code__.co_varnames:
if i not in mkwargs:
mkwargs[i] = margs[j]
j = j + 1
return fire(**mkwargs)
def add(a, b, c):
print(a, b, c)
print(str(a + b + c))
return a + b + c
def fx(ya, ykw):
if len(ya) + len(ykw) == 3:
return True
return False
import unittest
class test1(unittest.TestCase):
def test_Basictest(self):
x = CurryingBase(add, fx)
self.assertEqual(x(1)(2)(3), 6)
def test_Complicatedtest(self):
x = CurryingBase(add, fx)
self.assertEqual(x(b=2)(1)(3), 6)
self.assertEqual(x(2)(a=1)(3), 6)
#unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment