I want to define a function, which would have dictionary like parameter, e.g.:
def my_func(params={'skip': True}):
print(params['skip'])
params['skip'] = False
However if a mutable dictionary dict() is used - it gets created only once for a function. And modifications made to that dictionary are present during the next call.
my_func() # prints True
my_func() # prints False
Currently the only idea I have is to use tuple of key/value pairs, which can be converted into a dictionary, instead of providing dictionary like data.
def my_func(params=(('skip', True))):
params = dict(params)
print(params['skip'])
params['skip'] = False
However, I would really like to avoid this explicit conversion to a dictionary.
My question is: Is there an Immutable dictionary alternative for dict() as there is tuple() for list()?
This would avoid having every call to func using the default params share the same dict (which seems to be your issue):
def my_func(params=None):
params = {'skip': True} if params==None else params
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