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

Simplify multiple calls to str.startswith / str.endswith #1760

Merged
merged 2 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
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
11 changes: 3 additions & 8 deletions gramps/gen/plug/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,12 +333,7 @@ def load_addon_file(path, callback=None):
"""
import tarfile

if (
path.startswith("http://")
or path.startswith("https://")
or path.startswith("ftp://")
or path.startswith("file://")
):
if path.startswith(("http://", "https://", "ftp://", "file://")):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if path.startswith(("http://", "https://", "ftp://", "file://")):
if path.lower().startswith(("http://", "https://", "ftp://", "file://")):

The protocol in a URI is case-insensitive. See https://www.rfc-editor.org/rfc/rfc3986#section-3.1

try:
fptr = urlopen_maybe_no_check_cert(path)
except:
Expand All @@ -361,9 +356,9 @@ def load_addon_file(path, callback=None):
return False
fptr.close()
# file_obj is either Zipfile or TarFile
if path.endswith(".zip") or path.endswith(".ZIP"):
if path.endswith((".zip", ".ZIP")):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if path.endswith((".zip", ".ZIP")):
if path.lower().endswith((".zip")):

would this be ever clearer and handle mixed case (.Zip etc.) correctly as well?

file_obj = Zipfile(buffer)
elif path.endswith(".tar.gz") or path.endswith(".tgz"):
elif path.endswith((".tar.gz", ".tgz")):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
elif path.endswith((".tar.gz", ".tgz")):
elif path.lower().endswith((".tar.gz", ".tgz")):

try:
file_obj = tarfile.open(None, fileobj=buffer)
except:
Expand Down
2 changes: 1 addition & 1 deletion gramps/gen/utils/grampslocale.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ def _get_translation(self, domain=None, localedir=None, languages=None):
translator.lang = lang
return translator

if lang.startswith("en") or lang.startswith("C"):
if lang.startswith(("en", "C")):
translator = GrampsNullTranslations()
translator.lang = "en"
return translator
Expand Down
9 changes: 2 additions & 7 deletions gramps/gui/plug/_windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -1254,7 +1254,7 @@ def __refresh_addon_list(self, obj):
pm.set_pass(total=len(lines), header=_("Reading gramps-project.org..."))
for line in lines:
pm.step()
if line.startswith("|-") or line.startswith("|}"):
if line.startswith(("|-", "|}")):
if row != []:
rows.append(row)
state = "row"
Expand Down Expand Up @@ -1308,12 +1308,7 @@ def __refresh_addon_list(self, obj):
url = download[1:-1]
if " " in url:
url, text = url.split(" ", 1)
if (
url.endswith(".zip")
or url.endswith(".ZIP")
or url.endswith(".tar.gz")
or url.endswith(".tgz")
):
if url.endswith((".zip", ".ZIP", ".tar.gz", ".tgz")):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if url.endswith((".zip", ".ZIP", ".tar.gz", ".tgz")):
if url.lower().endswith((".zip", ".ZIP", ".tar.gz", ".tgz")):

# Then this is ok:
self.addon_model.append(
row=[
Expand Down
8 changes: 3 additions & 5 deletions gramps/plugins/lib/libgedcom.py
Original file line number Diff line number Diff line change
Expand Up @@ -1006,10 +1006,8 @@ def __readahead(self):
line_value = line[2].lstrip()
# Ignore meaningless @IDENT@ on CONT or CONC line
# as noted at http://www.tamurajones.net/IdentCONT.xhtml
if line_value.lstrip().startswith(
"CONT "
) or line_value.lstrip().startswith("CONC "):
line = line_value.lstrip().partition(" ")
if line_value.startswith(("CONT ", "CONC ")):
line = line_value.partition(" ")
tag = line[0]
line_value = line[2]
else:
Expand Down Expand Up @@ -4009,7 +4007,7 @@ def __parse_record(self):
self.__check_msgs(_("Top Level"), state, None)
elif key in ("SOUR", "SOURCE"):
self.__parse_source(line.token_text, 1)
elif line.data.startswith("SOUR ") or line.data.startswith("SOURCE "):
elif line.data.startswith(("SOUR ", "SOURCE ")):
# A source formatted in a single line, for example:
# 0 @S62@ SOUR This is the title of the source
source = self.__find_or_create_source(self.sid_map[line.data])
Expand Down
6 changes: 2 additions & 4 deletions gramps/plugins/webreport/basepage.py
Original file line number Diff line number Diff line change
Expand Up @@ -2746,15 +2746,13 @@ def display_url_list(self, urllist=None):

# Web Site address
elif _type == UrlType.WEB_HOME:
if not (
uri.startswith("http://") or uri.startswith("https://")
):
if not uri.startswith(("http://", "https://")):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if not uri.startswith(("http://", "https://")):
if not uri.lower().startswith(("http://", "https://")):

url = self.secure_mode
uri = url + "%(website)s" % {"website": uri}

# FTP server address
elif _type == UrlType.WEB_FTP:
if not (uri.startswith("ftp://") or uri.startswith("ftps://")):
if not uri.startswith(("ftp://", "ftps://")):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if not uri.startswith(("ftp://", "ftps://")):
if not uri.lower().startswith(("ftp://", "ftps://")):

uri = "ftp://%(ftpsite)s" % {"ftpsite": uri}

descr = Html("p", html_escape(descr)) + (
Expand Down
15 changes: 3 additions & 12 deletions gramps/plugins/webreport/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@

import gramps.plugins.lib.libholiday as libholiday
from gramps.plugins.webreport.basepage import BasePage
from gramps.plugins.webreport.common import do_we_have_holidays, _WEB_EXT
from gramps.plugins.webreport.common import do_we_have_holidays, _has_webpage_extension
from gramps.plugins.lib.libhtml import Html # , xml_lang
from gramps.gui.pluginmanager import GuiPluginManager

Expand Down Expand Up @@ -280,8 +280,8 @@ def month_navigation(self, nr_up, year, currentsection):
url_fname = url_fname.lower()
url = url_fname
add_subdirs = False
if not (url.startswith("http:") or url.startswith("/")):
add_subdirs = not any(url.endswith(ext) for ext in _WEB_EXT)
if not url.startswith(("http:", "/")):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if not url.startswith(("http:", "/")):
if not url.lower().startswith(("http:", "/")):

add_subdirs = not _has_webpage_extension(url)

# whether to add subdirs or not???
if add_subdirs:
Expand Down Expand Up @@ -1348,15 +1348,6 @@ def get_first_day_of_month(year, month):
return current_date, current_ord, monthinfo


def _has_webpage_extension(url):
"""
determine if a filename has an extension or not...

url = filename to be checked
"""
return any(url.endswith(ext) for ext in _WEB_EXT)


def get_day_list(event_date, holiday_list, bday_anniv_list, rlocale=glocale):
"""
Will fill day_list and return it to its caller: calendar_build()
Expand Down
4 changes: 2 additions & 2 deletions gramps/plugins/webreport/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
# define clear blank line for proper styling
FULLCLEAR = Html("div", class_="fullclear", inline=True)
# define all possible web page filename extensions
_WEB_EXT = [".html", ".htm", ".shtml", ".php", ".cgi"]
_WEB_EXT = (".html", ".htm", ".shtml", ".php", ".cgi")
# used to select secured web site or not
HTTP = "http://"
HTTPS = "https://"
Expand Down Expand Up @@ -708,7 +708,7 @@ def _has_webpage_extension(url):

@param: url -- filename to be checked
"""
return any(url.endswith(ext) for ext in _WEB_EXT)
return url.endswith(_WEB_EXT)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return url.endswith(_WEB_EXT)
return url.lower().endswith(_WEB_EXT)



def add_birthdate(dbase, ppl_handle_list, rlocale):
Expand Down
8 changes: 4 additions & 4 deletions gramps/plugins/webreport/webcal.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@
FULLCLEAR = Html("div", class_="fullclear", inline=True)

# Web page filename extensions
_WEB_EXT = [".html", ".htm", ".shtml", ".php", ".php3", ".cgi"]
_WEB_EXT = (".html", ".htm", ".shtml", ".php", ".php3", ".cgi")

# Calendar stylesheet names
_CALENDARSCREEN = "calendar-screen.css"
Expand Down Expand Up @@ -709,8 +709,8 @@ def month_navigation(self, nr_up, year, currentsection):
url_fname = url_fname.lower()
url = url_fname
add_subdirs = False
if not (url.startswith("http:") or url.startswith("/")):
add_subdirs = not any(url.endswith(ext) for ext in _WEB_EXT)
if not url.startswith(("http:", "/")):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if not url.startswith(("http:", "/")):
if not url.lower().startswith(("http:", "/")):

add_subdirs = not _has_webpage_extension(url)

# whether to add subdirs or not???
if add_subdirs:
Expand Down Expand Up @@ -2238,7 +2238,7 @@ def _has_webpage_extension(url):

url = filename to be checked
"""
return any(url.endswith(ext) for ext in _WEB_EXT)
return url.endswith(_WEB_EXT)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return url.endswith(_WEB_EXT)
return url.lower().endswith(_WEB_EXT)



def get_day_list(event_date, holiday_list, bday_anniv_list, rlocale=glocale):
Expand Down
2 changes: 1 addition & 1 deletion gramps/test/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def delete_tree(dir):
sdir = os.path.abspath(dir)
here = _caller_dir() + os.path.sep
tmp = tempfile.gettempdir() + os.path.sep
if not (sdir.startswith(here) or sdir.startswith(tmp)):
if not sdir.startswith((here, tmp)):
raise TestError("%r is not a subdir of here (%r) or %r" % (dir, here, tmp))
shutil.rmtree(sdir)

Expand Down
10 changes: 5 additions & 5 deletions po/update_po.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ def create_filesfile():

for filename in os.listdir(dirpath):
name = os.path.split(filename)[1]
if name.endswith(".py") or name.endswith(".glade"):
if name.endswith((".py", ".glade")):
full_filename = os.path.join(dirpath, filename)
# Skip the file if in POTFILES.skip
if full_filename[lentopdir:] in notinfiles:
Expand Down Expand Up @@ -430,13 +430,13 @@ def xml_fragments():
tokens = tokenize(fp.readline)
in_string = False
for _token, _text, _start, _end, _line in tokens:
if _text.startswith('"""') or _text.startswith("'''"):
if _text.startswith(('"""', "'''")):
_text = _text[3:]
elif _text.startswith('"') or _text.startswith("'"):
elif _text.startswith(('"', "'")):
_text = _text[1:]
if _text.endswith('"""') or _text.endswith("'''"):
if _text.endswith(('"""', "'''")):
_text = _text[:-3]
elif _text.endswith('"') or _text.endswith("'"):
elif _text.endswith(('"', "'")):
_text = _text[:-1]
if _token == STRING and not in_string:
in_string = True
Expand Down
Loading