Proteusiq / hadithi

🧪 Data Science | ⚒️ MLOps | ⚙️ DataOps : Talks about 🦄

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Misc

Proteusiq opened this issue · comments

Ideas

# closure, partials, decorator

# we would like to prepopulate value before calling a function
from typing import Callable

FunctionType = Callable[[str, int], str]


# using closure
def function_closure(age: int) -> FunctionType:
	def function(*, name: str, age: int=age) -> str:
		return f'Name {name} | Age {age}'

	return function


function_c = function_closure(age=42)
print(function_c(name='James'))

# using partials 
from functools import partial


def function(*, name: str, age: int) -> str:
	return f'Name {name} | Age {age}'


function_p = partial(function, age=42)
print(function_p(name='James'))

# using decorators
from functools import wraps


def fill(age: int) -> Callable:
	def outer_wrap(func: FunctionType) -> FunctionType:
		@wraps(func)
		def inner_wrap(**kwargs):
			return func(age=age, **kwargs)

		return inner_wrap

	return outer_wrap


@fill(age=42)
def function(*, name: str, age: int) -> str:
	return f'Name {name} | Age {age}'


print(function(name='James'))