Skip to content

Commit

Permalink
Handle in JSON (pre-init) instead of post-init to preserve lazy initi…
Browse files Browse the repository at this point in the history
…alization
  • Loading branch information
JWCook committed Jul 23, 2024
1 parent 2c279d9 commit 0c52306
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions pyinaturalist/models/observation.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,22 +319,18 @@ def __init__(self, **kwargs):
# Set identifications_count if missing
if kwargs.get('identifications') and not kwargs.get('identifications_count'):
kwargs['identifications_count'] = len(kwargs['identifications'])
self.__attrs_init__(**kwargs) # type: ignore

def __attrs_post_init__(self):
"""Add ancestor info to Observation.taxon based on identification data, if available."""
if not self.taxon or not self.identifications:
return

taxa_by_id = {
t.id: t
for t in chain.from_iterable(
[i.taxon.ancestors for i in self.identifications if i.taxon]
)
}
self.taxon.ancestors = list(
filter(None, [taxa_by_id.get(i) for i in self.taxon.ancestor_ids])
)
# Add ancestor info to Observation.taxon based on identification data, if available
if kwargs.get('taxon') and (idents := kwargs.get('identifications')):
taxa_by_id = {
t['id']: t
for t in chain.from_iterable(
[i.get('taxon', {}).get('ancestors', []) for i in idents]
)
}
ancestors = [taxa_by_id.get(i) for i in kwargs['taxon'].get('ancestor_ids')]
kwargs['taxon']['ancestors'] = list(filter(None, ancestors))
self.__attrs_init__(**kwargs) # type: ignore

@property
def cumulative_ids(self) -> Tuple[int, int]:
Expand Down

0 comments on commit 0c52306

Please sign in to comment.