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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With