Autogen
Jump to navigation
Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
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]
- 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, asmax('10.1', '9.0') == '9.0'
. Better code would bekey=lambda item: tuple(map(int, re.findall('\d+', x["tag_name"])))
, because python sorts tuples of integers correctly. - Next, selecting maximal element by sorting a list and then selecting the rightmost element is not very beautiful.
sorted
can be replaced bymax
:return max(releases, key=extract_version)
max
can return default value, when there are no element, so checkif not len(releases)
becomes needless:return max(releases, key=version, default=None)
x["prerelease"] is False
check is considered unpythonic. Usenot x["prerelease"]
not "Android" in x["name"]
is two operators, that can be combined:"Android" not in x["name"]
- 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)