Extra parentheses when calling a nested function in Python

I study the Mark Pilgrim Dive Into Python Book module in Chapter 6, and I’m kind of stuck with what this line of code does return [getFileInfoClass(f)(f) for f in fileList] . getFileInfo is a nested function, and I was wondering what duplicate (f) is, extra brackets. I was hoping someone could help me. Here's the full 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] 
+6
source share
2 answers

getFileInfoClass returns a class ; the classes themselves are then called - calling class only by name returns an instance of it. Two pairs of partners in quick succession are simply reduced. It is effective:

 file_info_class = getFileInfoClass(f) file_info_instance = file_info_class(f) 

As a rule, two pairs of such partners are probably a dubious decision, since it is not very readable, but I believe that in this case the author considered it reasonable, because it allowed him or her to put everything into a single understanding of the list.

+7
source

getFileInfoClass returns a class, so getFileInfoClass(f) is a class. When you take the class name and write the brackets after it, you call the constructor.

So, [getFileInfoClass(f)(f) for f in fileList] creates a list of FileInfo objects.

+3
source

Source: https://habr.com/ru/post/985402/


All Articles