python - How does this specific section of code work? -


def add_info_extractor(self, ie):     """add infoextractor object end of list."""     self._ies.append(ie)     if not isinstance(ie, type):         self._ies_instances[ie.ie_key()] = ie         ie.set_downloader(self)  def get_info_extractor(self, ie_key):     """     instance of ie name ie_key, try 1     _ies list, if there's no instance create new 1 , add     extractor list.     """     ie = self._ies_instances.get(ie_key)     if ie none:         ie = get_info_extractor(ie_key)()         self.add_info_extractor(ie)     return ie 

the following taken popular python repo, youtube-dl. in effor become better programmer cam across section , i'm having trouble understanding it.

particularly last method , how not enter infinite recursion if ie_key not found in list.

as isinstance comparision in first method.

i understand normal implementation effect of: isinstance('hello', str) , how can type() type? what's point of comparing ie object type?

this cause infinite recursion. no updates seem happen self._ies_instances in between recursive calls, , recursion dependent on case, continue.

maybe bug, code has never had situation when ie_key not in dictionary?

as confusion type, it's result of python metaclasses (a great read). type acts both "function" return type of object as as class create new type (when called more arguments).

one reason may want check see if instance of type see if metaclass:

>>> isinstance(1, type) false >>> isinstance("", type) false >>> isinstance({}, type) false >>> isinstance((), type) false >>> type(object) == type true >>> isinstance(object, type) true >>> isinstance(object(), type) false >>> class a(): pass ... >>> isinstance(a, type) false >>> isinstance(a(), type) false 

as object 'base new style classes' (docs), acts metaclass (as shown above).


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -