'isinstance with docx.Document class

in a script I want to run certain lines when a variable is of type Document. However this check always returns false, no matter the input.

from docx import Document
from docx import Document as _Document

document = Document('use_this_doc.docx') 
isinstance (document, _Document)

type(document) returns docx.document.Document

isinstance(document, _Document) returns False, while I would expect it to return True. isinstance(document, type(Document)) also returns False.

How can I adjust the code for it to return True in the case as specified?



Solution 1:[1]

Document is a helper function to open a document. It returns an object of type docx.document.Document.

docx.Document (a function) is not the same as docx.document.Document (a type).

Calling isinstance(document, Document) would generate an error because the second argument must be a type.

from docx import Document
import docx
print("docx.Document =>", type(docx.Document))
print("docx.document.Document =>", type(docx.document.Document))
document = Document('use_this_doc.docx') 
print(type(document), isinstance(document, docx.document.Document))

Output:

docx.Document => <class 'function'>
docx.document.Document => <class 'type'>

<class 'docx.document.Document'> True

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1