Skip to content

Instantly share code, notes, and snippets.

@chartjes
Created December 30, 2015 15:45
Show Gist options
  • Save chartjes/b2679917364f0e4ae913 to your computer and use it in GitHub Desktop.
Save chartjes/b2679917364f0e4ae913 to your computer and use it in GitHub Desktop.
There must be a more idiomatic way
for container in containers:
p1 = re.compile('.*?kinto_read-only_(\d)$')
p2 = re.compile('.*?kinto_master_(\d)$')
print container['Names']
if container['Names']:
for name in container['Names']:
if p1.match(name):
ports = container['Ports']
for port in ports:
self.read_only['ip'] = port['IP']
self.read_only['port'] = port['PrivatePort']
if p2.match(name):
ports = container['Ports']
for port in ports:
self.master['ip'] = port['IP']
self.master['port'] = port['PrivatePort']
@josegonzalez
Copy link

_RE_READ_ONLY = re.compile('.*?kinto_read-only_(\d)$')
_RE_MASTER = re.compile('.*?kinto_master_(\d)$')

def get_ports(self, containers):
    # use a list comprehension to filter out containers with names
    containers = [container for container in containers if 'Names' in container]
    for container in containers:
        if has_match(_RE_READ_ONLY, container['Names']):
            # seems like you are overriding, do you only want the last one?
            for port in container.get('Ports', {}):
                self.read_only['ip'] = port['IP']
                self.read_only['port'] = port['PrivatePort']

        if has_match(_RE_MASTER, container['Names']):
            for port in container.get('Ports', {}):
                self.master['ip'] = port['IP']
                self.master['port'] = port['PrivatePort']


def has_match(r, names):
    # check using a list comprehension
    return true in [true for name in names if r.match(name)]

@tarekziade
Copy link

nitpick: I would not use list comprehensions to filter out things, because it means you are looping over the whole list at most twice -- which is suboptimal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment