Micro-optimization: replace s.find(x)!=-1 with x in s

timeit shows a speedup of ~3x on Python 2.7.5 x86_64.
It also makes the code a bit shorter.
This commit is contained in:
Cristian Ciupitu
2014-01-23 17:02:17 +02:00
committed by Michael DeHaan
parent a7da5d8702
commit 0749112286
19 changed files with 50 additions and 48 deletions

View File

@@ -250,7 +250,7 @@ def regular_generic_msg(hostname, result, oneline, caption):
def banner_cowsay(msg):
if msg.find(": [") != -1:
if ": [" in msg:
msg = msg.replace("[","")
if msg.endswith("]"):
msg = msg[:-1]

View File

@@ -69,7 +69,7 @@ class InventoryParser(object):
line = utils.before_comment(line).strip()
if line.startswith("[") and line.endswith("]"):
active_group_name = line.replace("[","").replace("]","")
if line.find(":vars") != -1 or line.find(":children") != -1:
if ":vars" in line or ":children" in line:
active_group_name = active_group_name.rsplit(":", 1)[0]
if active_group_name not in self.groups:
new_group = self.groups[active_group_name] = Group(name=active_group_name)
@@ -95,11 +95,11 @@ class InventoryParser(object):
# FQDN foo.example.com
if hostname.count(".") == 1:
(hostname, port) = hostname.rsplit(".", 1)
elif (hostname.find("[") != -1 and
hostname.find("]") != -1 and
hostname.find(":") != -1 and
elif ("[" in hostname and
"]" in hostname and
":" in hostname and
(hostname.rindex("]") < hostname.rindex(":")) or
(hostname.find("]") == -1 and hostname.find(":") != -1)):
("]" not in hostname and ":" in hostname)):
(hostname, port) = hostname.rsplit(":", 1)
hostnames = []
@@ -152,7 +152,7 @@ class InventoryParser(object):
line = line.strip()
if line is None or line == '':
continue
if line.startswith("[") and line.find(":children]") != -1:
if line.startswith("[") and ":children]" in line:
line = line.replace("[","").replace(":children]","")
group = self.groups.get(line, None)
if group is None:
@@ -177,7 +177,7 @@ class InventoryParser(object):
group = None
for line in self.lines:
line = line.strip()
if line.startswith("[") and line.find(":vars]") != -1:
if line.startswith("[") and ":vars]" in line:
line = line.replace("[","").replace(":vars]","")
group = self.groups.get(line, None)
if group is None:
@@ -189,7 +189,7 @@ class InventoryParser(object):
elif line == '':
pass
elif group:
if line.find("=") == -1:
if "=" not in line:
raise errors.AnsibleError("variables assigned to group must be in key=value form")
else:
(k, v) = [e.strip() for e in line.split("=", 1)]

View File

@@ -95,7 +95,7 @@ class ModuleReplacer(object):
for line in lines:
if line.find(REPLACER) != -1:
if REPLACER in line:
output.write(self.slurp(os.path.join(self.snippet_path, "basic.py")))
snippet_names.append('basic')
elif line.startswith('from ansible.module_utils.'):
@@ -103,7 +103,7 @@ class ModuleReplacer(object):
import_error = False
if len(tokens) != 3:
import_error = True
if line.find(" import *") == -1:
if " import *" not in line:
import_error = True
if import_error:
raise errors.AnsibleError("error importing module in %s, expecting format like 'from ansible.module_utils.basic import *'" % module_path)

View File

@@ -707,7 +707,7 @@ class Play(object):
# *************************************************
def _has_vars_in(self, msg):
return ((msg.find("$") != -1) or (msg.find("{{") != -1))
return "$" in msg or "{{" in msg
# *************************************************

View File

@@ -415,7 +415,7 @@ class Runner(object):
environment_string = self._compute_environment_string(inject)
if tmp.find("tmp") != -1 and ((self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root')):
if "tmp" in tmp and ((self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root')):
# deal with possible umask issues once sudo'ed to other user
cmd_chmod = "chmod a+r %s" % remote_module_path
self._low_level_exec_command(conn, cmd_chmod, tmp, sudoable=False)
@@ -469,7 +469,7 @@ class Runner(object):
cmd = " ".join([environment_string.strip(), shebang.replace("#!","").strip(), cmd])
cmd = cmd.strip()
if tmp.find("tmp") != -1 and not C.DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp:
if "tmp" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp:
if not self.sudo or self.su or self.sudo_user == 'root' or self.su_user == 'root':
# not sudoing or sudoing to root, so can cleanup files in the same step
cmd = cmd + "; rm -rf %s >/dev/null 2>&1" % tmp
@@ -485,7 +485,7 @@ class Runner(object):
else:
res = self._low_level_exec_command(conn, cmd, tmp, sudoable=sudoable, in_data=in_data)
if tmp.find("tmp") != -1 and not C.DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp:
if "tmp" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp:
if (self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root'):
# not sudoing to root, so maybe can't delete files as that other user
# have to clean up temp files as original user in a second step
@@ -883,7 +883,7 @@ class Runner(object):
return False
def _late_needs_tmp_path(self, conn, tmp, module_style):
if tmp.find("tmp") != -1:
if "tmp" in tmp:
# tmp has already been created
return False
if not conn.has_pipelining or not C.ANSIBLE_SSH_PIPELINING or C.DEFAULT_KEEP_REMOTE_FILES or self.su:

View File

@@ -33,7 +33,7 @@ class ActionModule(object):
module_name = 'command'
module_args += " #USE_SHELL"
if tmp.find("tmp") == -1:
if "tmp" not in tmp:
tmp = self.runner._make_tmp_path(conn)
(module_path, is_new_style, shebang) = self.runner._copy_module(conn, tmp, module_name, module_args, inject, complex_args=complex_args)

View File

@@ -331,7 +331,7 @@ class ActionModule(object):
src = open(source)
src_contents = src.read(8192)
st = os.stat(source)
if src_contents.find("\x00") != -1:
if "\x00" in src_contents:
diff['src_binary'] = 1
elif st[stat.ST_SIZE] > utils.MAX_FILE_SIZE_FOR_DIFF:
diff['src_larger'] = utils.MAX_FILE_SIZE_FOR_DIFF

View File

@@ -128,7 +128,7 @@ class ActionModule(object):
result = handler.run(conn, tmp, 'raw', module_args, inject)
# clean up after
if tmp.find("tmp") != -1 and not C.DEFAULT_KEEP_REMOTE_FILES:
if "tmp" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES:
self.runner._low_level_exec_command(conn, 'rm -rf %s >/dev/null 2>&1' % tmp, tmp)
result.result['changed'] = True

View File

@@ -68,9 +68,9 @@ class Connection(object):
cp_in_use = False
cp_path_set = False
for arg in self.common_args:
if arg.find("ControlPersist") != -1:
if "ControlPersist" in arg:
cp_in_use = True
if arg.find("ControlPath") != -1:
if "ControlPath" in arg:
cp_path_set = True
if cp_in_use and not cp_path_set:
@@ -137,7 +137,7 @@ class Connection(object):
data = host_fh.read()
host_fh.close()
for line in data.split("\n"):
if line is None or line.find(" ") == -1:
if line is None or " " not in line:
continue
tokens = line.split()
if tokens[0].find(self.HASHED_KEY_MAGIC) == 0:
@@ -324,7 +324,8 @@ class Connection(object):
# the host to known hosts is not intermingled with multiprocess output.
fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_UN)
fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_UN)
controlpersisterror = stderr.find('Bad configuration option: ControlPersist') != -1 or stderr.find('unknown configuration option: ControlPersist') != -1
controlpersisterror = 'Bad configuration option: ControlPersist' in stderr or \
'unknown configuration option: ControlPersist' in stderr
if C.HOST_KEY_CHECKING:
if ssh_cmd[0] == "sshpass" and p.returncode == 6:

View File

@@ -193,7 +193,7 @@ def check_conditional(conditional, basedir, inject, fail_on_undefined=False):
conditional = conditional.replace("jinja2_compare ","")
# allow variable names
if conditional in inject and str(inject[conditional]).find('-') == -1:
if conditional in inject and '-' not in str(inject[conditional]):
conditional = inject[conditional]
conditional = template.template(basedir, conditional, inject, fail_on_undefined=fail_on_undefined)
original = str(conditional).replace("jinja2_compare ","")
@@ -206,9 +206,9 @@ def check_conditional(conditional, basedir, inject, fail_on_undefined=False):
# variable was undefined. If we happened to be
# looking for an undefined variable, return True,
# otherwise fail
if conditional.find("is undefined") != -1:
if "is undefined" in conditional:
return True
elif conditional.find("is defined") != -1:
elif "is defined" in conditional:
return False
else:
raise errors.AnsibleError("error while evaluating conditional: %s" % original)
@@ -331,9 +331,9 @@ def parse_json(raw_data):
def smush_braces(data):
''' smush Jinaj2 braces so unresolved templates like {{ foo }} don't get parsed weird by key=value code '''
while data.find('{{ ') != -1:
while '{{ ' in data:
data = data.replace('{{ ', '{{')
while data.find(' }}') != -1:
while ' }}' in data:
data = data.replace(' }}', '}}')
return data
@@ -374,7 +374,7 @@ def parse_yaml(data, path_hint=None):
def process_common_errors(msg, probline, column):
replaced = probline.replace(" ","")
if replaced.find(":{{") != -1 and replaced.find("}}") != -1:
if ":{{" in replaced and "}}" in replaced:
msg = msg + """
This one looks easy to fix. YAML thought it was looking for the start of a
hash/dictionary and was confused to see a second "{". Most likely this was
@@ -542,7 +542,7 @@ def parse_kv(args):
vargs = [x.decode('utf-8') for x in shlex.split(args, posix=True)]
#vargs = shlex.split(str(args), posix=True)
for x in vargs:
if x.find("=") != -1:
if "=" in x:
k, v = x.split("=",1)
options[k]=v
return options
@@ -1023,7 +1023,7 @@ def listify_lookup_plugin_terms(terms, basedir, inject):
# not sure why the "/" is in above code :)
try:
new_terms = template.template(basedir, "{{ %s }}" % terms, inject)
if isinstance(new_terms, basestring) and new_terms.find("{{") != -1:
if isinstance(new_terms, basestring) and "{{" in new_terms.find:
pass
else:
terms = new_terms
@@ -1097,3 +1097,4 @@ def before_comment(msg):
return msg