Autogen

From Funtoo
Jump to: navigation, search

Typical autogen.py code:

   browser-kit/curated/www-client/brave-bin/autogen.py (python source code)
def find_release(json_dict, channel="Release"):
	releases = filter(
		lambda x: x["prerelease"] is False
		and x["draft"] is False
		and x["name"].startswith(channel)
		and not "Android" in x["name"],
		json_dict,
	)
	releases = list(releases)
	if not len(releases):
		return None
	return sorted(releases, key=lambda x: x["tag_name"])[-1]
  1. Let's start with the key argument. It allows to sort an array by specific key; tag_name in this example. tag_name is a version number that is stored as a string, so sorting won't work correctly, as max('10.1', '9.0') == '9.0'. Better code would be key=lambda item: tuple(map(int, re.findall('\d+', x["tag_name"]))), because python sorts tuples of integers correctly.
  2. Next, selecting maximal element by sorting a list and then selecting the rightmost element is not very beautiful. sorted can be replaced by max: return max(releases, key=extract_version)
  3. max can return default value, when there are no element, so check if not len(releases) becomes needless: return max(releases, key=version, default=None)
  4. x["prerelease"] is False check is considered unpythonic. Use not x["prerelease"]
  5. not "Android" in x["name"] is two operators, that can be combined: "Android" not in x["name"]
  6. Generator comprehension are considered more pythonic than filter.

So, more pythonic version, that works correctly looks like this:

   browser-kit/curated/www-client/brave-bin/autogen.py (python source code)
def extract_version(release):
	return tuple(map(int, re.findall('\d+', release["tag_name"])))

def find_release(all_releases, channel="Release"):
	releases = (
		release for release in all_releases
		if not release["prerelease"]
		and not release["draft"]
		and release["name"].startswith(channel)
		and "Android" not in release["name"]
	)
	return max(releases, key=extract_version)