Created
December 30, 2015 15:45
-
-
Save chartjes/b2679917364f0e4ae913 to your computer and use it in GitHub Desktop.
There must be a more idiomatic way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'] |
tarekziade
commented
Dec 30, 2015
something like this... ?
p1 = re.compile('.*?kinto_read-only_(\d)$')
p2 = re.compile('.*?kinto_master_(\d)$')
container_names = [c['Names'] for c in containers if c['Names']]
ports_by_name = {c['Names']: c['Ports'][-1] for c in containers if c['Names']}
for container_name in container_names:
if p1.match(container_name):
self.read_only['ip'] = ports_by_name[container_name]['IP'][-1]
self.read_only['port'] = ports_by_name[container_name]['PrivatePort'][-1]
elif p2.match(container_name):
self.master['ip'] = ports_by_name[container_name]['IP'][-1]
self.master['port'] = ports_by_name[container_name]['PrivatePort'][-1]
_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)]
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