Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An extra parentheses in a call to a nested function in Python

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]
like image 382
user3243986 Avatar asked Apr 18 '15 04:04

user3243986


2 Answers

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.

like image 125
jwilner Avatar answered Oct 03 '22 23:10

jwilner


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.

like image 41
justanothercoder Avatar answered Oct 03 '22 23:10

justanothercoder