Skip to content

Instantly share code, notes, and snippets.

@michaelsproul
Last active January 3, 2016 17:49
Show Gist options
  • Save michaelsproul/8498543 to your computer and use it in GitHub Desktop.
Save michaelsproul/8498543 to your computer and use it in GitHub Desktop.
Python WTF
# This is the weirdest shit I have ever seen in Python.
# If you call this on a list of directories containing only .cpp files, it's fine.
# If any of the directories contain .c files, there are instant errors!!
# E.g:
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "python_wtf.py", line 18, in get_objects
# objects.extend([c_filter(x) for x in c_files])
# File "python_wtf.py", line 18, in <listcomp>
# objects.extend([c_filter(x) for x in c_files])
# NameError: global name 'c_filter' is not defined
# Why does this work for one function, but not for the other??!
# Problem solved. It was a typo.
import glob
def get_objects(directories):
"""Get the names of all the .o files in the given directories."""
# Filter functions, to turn source filepaths into object filenames
c_filter = lambda x: x.split("/")[-1].replace(".c", ".o")
cpp_filter = lambda x: x.split("/")[-1].replace(".cpp", ".o")
objects = []
for directory in directories:
c_files = glob.glob("%s/*.c" % directory)
objects.extend([c_filter(x) for x in c_files])
cpp_files = glob.glob("%s/*.cpp" % directory)
objects.extend([cpp_filter(x) for x in cpp_files])
return objects
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment