The following excerpt is part of a method for recursively patching the properties of an ORM model and related models using a dictionary:
try:
anhaenge = d['anhaenge']
except KeyError:
self.logger.debug('anhaenge unchanged')
else:
try:
anhang = anhaenge['anhang']
except KeyError:
self.logger.debug('anhaenge.anhang unchanged')
except TypeError: # anhaenge is probably None
for record in self.anhang:
yield (record, PatchMode.DELETE)
else:
for record in self.anhang:
yield (record, PatchMode.DELETE)
if anhang:
for anhang_ in anhang:
with suppress(EmptyDict):
for record in Anhang.from_dict(
anhang_, immobilie=self):
yield (record, PatchMode.CREATE)
I currently violate the don't repeat yourself (DRY) principle, since I do the very same operation within the block handling the TypeError
and at the beginning of the inner else
block.
How can I resolve this to have the code
for record in self.anhang:
yield (record, PatchMode.DELETE)
only once?
Clarifying the input:
The inputd
is a dictionary derived by json.loads()
from a JSON string through a web API.
The method, the above excerpt is extracted from uses this dictionary to modify database records represented by the ORM model this methods belongs to.
Examples of d
:
# Delete all subsequent anhang records
d = {'anhaenge': {
'anhang': None}}
# Change all related anhang records to those represented by the dicts in
# the list, meaning:
# 1) Delete all old records
# 2) Create new ones from the dicts
d = {'anhaenge': {
'anhang': [
{'anhangtitel': 'Attachment1'},
{'anhangtitel': 'Attachment2'}]}}
# All subsequent anhang records are left as they are.
# Subsequent foo records may be altered accordingly
d = {'anhaenge': {
'foo': 'bar'}}
{'anhaenge': None}
work? – Peilonrayz Nov 9 at 14:56anhaenge
record and all its related records (contains also other amongstanhang
). This is essentially the reason for theTypeError
block. – Richard Neumann 2 days agoTypeError
block does more than what you show here? – Mathias Ettinger 2 days agoelse
block, below the innertry... except... else...
there come furthertry... except... else...
blocks similar to this one for other sub-keys ofanhaenge
. – Richard Neumann 2 days ago