Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add apply method #26

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions src/trackteroid/entities/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -820,9 +820,6 @@ def _is_attribute_compatible_with_value(self, attribute_name, value):
)
return compatible, reason

# TODO: Allow assignment of single value to multiple receivers.
# If is_array is true, we have to make sure, that the receiver either supports
# a collection or we have to check if the value only contains a single value
if isinstance(value, (EntityCollection, tuple, list)):
_reason = (
"When setting an attribute on a receiver collection, "
Expand Down Expand Up @@ -1118,6 +1115,35 @@ def filter(self, predicate):
else:
return EmptyCollection(_type=self._entity, source=self._get_parent(self), session=self._session)

def put(self, predicate, attribute_name=None):
"""Applies a predicate function to each entity in the collection and
assigns the generated value to the specified attribute.
If no attribute name is provided, the value is directly assigned to the calling collection.

Examples:
>>> some_collection.put(lambda c: c.another_attr[0] + "_edited", "some_attr")
>>> assetversion_collection.Task.Status.put(status_collection)

Args:
predicate (callable): A callable function that receives a single entity collection.
The return value of the function will be applied to the specified attribute.
attribute_name (optional: str): The name of the attribute to which the generated value will be assigned
or None

Returns:
EntityCollection: the updated collection

"""
if not attribute_name:
attribute_name, collection = self._source
else:
collection = self

for entitycollection in collection:
setattr(entitycollection, attribute_name, predicate(entitycollection))

return getattr(collection, attribute_name)

@staticmethod
def _get_parent(entitycollection):
parent_relation = entitycollection._entity.relationship.parent or "parent"
Expand Down