On 25.05.2016 16:06, Ian Foote wrote:
I can see this being useful if I have a Django Rest Framework
validate method (http://www.django-rest-framework.org/api-guide/serializers/#object-level-validation)
which takes a dictionary argument.
def validate(self, data):
{'name': name, 'address': address} = data
Currently, this would look like:
def validate(self, data):
name, address = data['name'], data['address']
Now, that you mention it (the restframework), I remember a concrete
usecase for our systems as well. We receive a YAML resource (via the
restframework -- that's the association) and we know it must be a
dict and contain several items. Additionally, we need the remaining
items to store somewhere else depending on some of the received
data.
{'needed1': needed1, 'needed2': needed2, **rest} = yaml_data
store_there(needed1, rest)
store_somewhere(needed2, rest)
Please note, that needed1 and needed2 are not allowed to be part of
the data which is supposed to be stored. These are mere flags.
It does get more useful with the extension:
def validate(self, data):
{'name': name, 'address': address, **rest} = data
@Michael
Does using ** instead of * seem more appropriate?
instead of:
def validate(self, data):
rest = data.copy()
name = rest.pop('name')
address = rest.pop('address')
In the rest framework case, mutating data directly might not be a
problem, but this does feel like a nice syntax when avoiding
mutation is required.
Regards,
Ian
Best,
Sven