Page Menu
Home
Software Heritage
Search
Configure Global Search
Log In
Paste
P807
mutable default arguments don't have to be an issue
Active
Public
Actions
Authored by
vlorentz
on Oct 7 2020, 12:28 PM.
Edit Paste
Archive Paste
View Raw File
Subscribe
Mute Notifications
Award Token
Flag For Later
Tags
None
Subscribers
None
import
copy
import
functools
from
typing
import
Callable
,
TypeVar
T
=
TypeVar
(
"T"
,
bound
=
Callable
)
def
copydefaults
(
f
:
T
)
->
T
:
original_defaults
=
f
.
__defaults__
@functools.wraps
(
f
)
def
newf
(
*
args
,
**
kwargs
):
f
.
__defaults__
=
copy
.
deepcopy
(
original_defaults
)
return
f
(
*
args
,
**
kwargs
)
return
newf
@copydefaults
def
f
(
key
,
d
=
{}):
d
[
key
]
=
42
return
d
print
(
f
(
"foo"
))
# {'foo': 42}
print
(
f
(
"bar"
))
# {'bar': 42}
Event Timeline
vlorentz
created this paste.
Oct 7 2020, 12:28 PM
2020-10-07 12:28:54 (UTC+2)
Log In to Comment