I'm studying the module of Mark Pilgrim's Dive Into Python Book in chapter 6, and I'm kind of stuck with what this line of code return [getFileInfoClass(f)(f) for f in fileList]
does. getFileInfo is a nested function and I was wondering what's the duplicate (f), the extra parentheses is for. I was hoping someone can help me out. Here's the complete function:
def listDirectory(directory, fileExtList):
"get list of file info objects for files of particular extensions"
fileList = [os.path.normcase(f) for f in os.listdir(directory)]
fileList = [os.path.join(directory, f) for f in fileList \
if os.path.splitext(f)[1] in fileExtList]
def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):
"get file info class from filename extension"
subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
return [getFileInfoClass(f)(f) for f in fileList]
getFileInfoClass
returns a class
; classes are then callable themselves -- calling a class
by just a name returns an instance of it. The two pairs of parens in quick succession are just shorthand. It is effectively:
file_info_class = getFileInfoClass(f)
file_info_instance = file_info_class(f)
Generally, the two pairs of parens like that is probably a questionable decision, as it's not very readable, but I suppose in this case the writer deemed it reasonable because it allowed him or her to put everything inside a single list comprehension.
getFileInfoClass
returns a class, so getFileInfoClass(f)
is a class. When you take a class name and write parentheses after it, you call a constructor.
So, [getFileInfoClass(f)(f) for f in fileList]
makes a list of FileInfo
objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With