Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

partial: disallow overriding given keyword arguments

Is there a way to disallow overriding given keyword arguments in a partial? Say I want to create function bar which always has a set to 1. In the following code:

from functools import partial

def foo(a, b):
  print(a)
  print(b)

bar = partial(foo, a=1)
bar(b=3) # This is fine and prints 1, 3
bar(a=3, b=3) # This prints 3, 3

You can happily call bar and set a to 3. Is it possible to create bar out of foo and make sure that calling bar(a=3, b=3) either raises an error or silently ignores a=3 and keeps using a=1 as in the partial?

like image 231
Jan Rüegg Avatar asked Dec 30 '22 19:12

Jan Rüegg


1 Answers

Do you really need to use partial? You can just define a new function bar normally with fewer arguments.

Like:

def bar(a):
  b = 1
  foo(a, b)

This will give error.

Or like:

def bar(a, b=1):
  b = 1 #ignored provided b
  foo(a, b)

This will ignore b.

EDIT: use lambda if you want to oneline these: like: bar = lambda a:foo(a,b=1) or bar = lambda a,b=1:foo(a,b=1)

like image 52
Atreyagaurav Avatar answered Jan 06 '23 01:01

Atreyagaurav