Assigning value to a dictionary variable that is optional

15

I have a function where one of the parameters is a dictionary, but it is optional.

I need to assign a value in this dictionary, but take into account the case where this parameter is not filled in.

The following solution uses two lines for this:

def uma_funcao(um_dict=None):
    um_dict = um_dict or {}
    um_dict['uma_chave'] = True

I believe there is a more Pythonic way of doing this, in one line. Is it possible?

    
asked by anonymous 17.12.2013 / 18:45

3 answers

12

No, I believe that this form you presented is already minimal. I can not talk about Python 3, as I have no experience.

(Answers in the negative are complicated, but I have no evidence to support it except the absence of evidence to the contrary ...)

Update: As 3 people have already posted the same incorrect answer, I'll point it out here to avoid future identical responses.

>>> def uma_funcao(um_dict={}):
...   um_dict['uma_chave'] = True
...   return um_dict
...
>>> x = uma_funcao()
>>> x['teste'] = True
>>> y = uma_funcao()
>>> y
{'uma_chave': True, 'teste': True}

As you can see, you should not use a changeable value as a default parameter for a function. The expression {} creates a before object to use as a parameter, so any call of uma_funcao without passing parameters will use the same < dict . Since this is seldom the desired behavior, there is no option but to use None followed by a test, just like the original question code.

Another way I thought of it, very common in languages like C, was to merge the assignment with use into a single expression:

(um_dict = um_dict or {})['uma_chave'] = True

However this is not allowed by the Python syntax (at least 2, if something like this has been added in future versions, it is not known to me).

    
17.12.2013 / 18:54
1

Is not this good here?

def uma_funcao(um_dict = {}):
  um_dict['uma_chave'] = True
  return um_dict

I do not understand why you assign None instead of assigning {} directly. If there is any reason for this, please go into more detail.

    
17.12.2013 / 19:42
1

One way to get around the problem presented by @mgibsonbr is to return a copy of the dictionary instead of it:

def uma_funcao(um_dict={}):
    um_dict['uma_chave'] = True
    return um_dict.copy()

Note that if um_dict is passed, it will continue to be modified:

>>> def uma_funcao(um_dict={}):
...   um_dict['uma_chave'] = True
...   return um_dict.copy()
...
>>> x = uma_funcao()
>>> x['teste'] = True
>>> y = uma_funcao()
>>> y
{'uma_chave': True}
>>> d = {'uma_chave': False}
>>> z = uma_funcao(d)
>>> z
{'uma_chave': True}
>>> d
{'uma_chave': True}

It is possible to do everything in a single line, even though it is far from being considered something pythonic:

def uma_funcao(um_dict={}):
    return um_dict.update({'uma_chave': True}) or um_dict.copy()
    
23.12.2013 / 04:53