Dealing with multiple **kwargs in Python

  • The ability to see parameters in Jupyter Notebooks
  • Minimal re-writing (no one likes copy-pasting default parameters everywhere — so we will aim to inherit these functions themselves)
class PaintMe:
def paint(self, color='red', number_of_letters=5):
self.color = color
self.print(
f"color is {color}",
number_of_letters=number_of_letters)

def verbose_print(self, string, number_of_letters=5):
print('print began')
print('a' * number_of_letters)
print(string)
print("print finished")
class PaintMeRainbow(PaintMe):
@delegates({"paint_kwargs": PaintMe.paint, "print_kwargs": PaintMe.verbose_print})
def rainbow_flag(self, print_kwargs={}, paint_kwargs={}):
self.print_verbose(**print_kwargs)
self.paint(**print_kwargs, **paint_kwargs)
PaintMeRainbow().rainbow_flag(
paint_kwargs={"color": "orange"},
print_kwargs={"number_of_letters": 10})
How this appears in a Jupyter Notebook — with the defaults already suggested
import inspect
def delegates(kwargs={}, keep=False):
"Decorator: replace `**kwargs` in signature with params from `to`"
def _f(f):
from_f = f
sig = inspect.signature(from_f)
sigd = dict(sig.parameters)
for name, kw in kwargs.items():
sigd[name] = inspect.Parameter(
name, inspect.Parameter.POSITIONAL_OR_KEYWORD,
default={k:v.default for k,v in inspect.signature(kw).parameters.items() if k not in sigd and
v.default != inspect.Parameter.empty})
if keep: sigd['kwargs'] = k
from_f.__signature__ = sig.replace(parameters=sigd.values())
return f
return _f

--

--

--

Founding Scientist/Engineer @ vctr.ai

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Stop manual API testing, automate with Postman!

Create a cheap http-proxy on GCP with terraform ( tutorial )

Frequently Asked Question in OfficeLand

Advantages and Limitations of Tableau Desktop

Azure Functions V2 Dependency Injection using .NET Core

Women detail drug use, sex and payments after late-night parties with Gaetz and others

ESP32, Cara Mengakses TelegramBot Kontrol Relay / Led

ESP32, Cara Mengakses TelegramBot Kontrol Relay / Led

CashFree Integration iOS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jacky Wong

Jacky Wong

Founding Scientist/Engineer @ vctr.ai

More from Medium

PyTest Use Cases

Using the U.S. Census Bureau API with Python

HackerRank: Solving Leap Years Puzzle Using Python

The easiest way to parallelize pandase