Skip to content

Instantly share code, notes, and snippets.

@jgosmann
Last active August 29, 2015 13:56
Show Gist options
  • Save jgosmann/8791216 to your computer and use it in GitHub Desktop.
Save jgosmann/8791216 to your computer and use it in GitHub Desktop.
List which broadcasts all operations to its elements.
class Broadcast(list):
"""List which broadcasts all operations to its elements."""
def __getattr__(self, name):
if name.startswith('__'):
# Necessary to allow easy casting to numpy arrays.
raise AttributeError(
"No implicit broadcast of attributes starting with '__'. Use "
"explicit call to broadcast().")
return self.broadcast(name)
def __setattr__(self, name, value):
for obj in self:
setattr(obj, name, value)
def __delattr__(self, name):
for obj in self:
delattr(obj, name)
def __call__(self, *args, **kwargs):
return Broadcast([f(*args, **kwargs) for f in self])
def broadcast(self, name):
return Broadcast(getattr(obj, name) for obj in self)
def __repr__(self):
return '{}({})'.format(
self.__class__.__name__, super(Broadcast, self).__repr__())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment