Home > Net >  isinstance with docx.Document class
isinstance with docx.Document class

Time:02-04

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?

CodePudding user response:

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

CodePudding user response:

You have created 2 identical classes with different names. An instance of Document is not an instance of _Document any more the an instance of A is an instance of B, even if the defenition of A and B are identical.

  •  Tags:  
  • Related