niekas
niekas

Reputation: 9097

Is there an Immutable dictionary type in Python?

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()?

Upvotes: 3

Views: 1573

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49803

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

Upvotes: 6

Related Questions