autodoc_pydantic: Numpy NDArray breaks inspection module

Thanks so much for this library! I’ve just discovered it.

autodoc_pydantic is crashing for me in inspection.py, where checking to see if “obj” is a subclass of “BaseModel”

All of the crashes are from checking various objects from numpy. The simplest reproducible example I found is:

import numpy as np
from numpy.typing import NDArray

>> issinstance(NDArray, type)  # returns True
>> issubclass(NDArray, BaseModel) # throws TypeError

As a workaround, I edited the file to put a try/except in is_pydantic_model:

459     @staticmethod                                                                                   
460     def is_pydantic_model(obj: Any) -> bool:                                                        
461         """Determine if object is a valid pydantic model.                                           
462                                                                                                     
463         """                                                                                         
464         try:                                                                                        
465             if isinstance(obj, type):                                                               
466                 return issubclass(obj, BaseModel)                                                   
467         except TypeError:                                                                                     
468             pass                                                                                    
469         return False         

The fallback behavior of returning False seems to work.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 17 (17 by maintainers)

Most upvoted comments

One more note which is interesting. This odd behaviour appears specifically with pydantic:

from pydantic import BaseModel
from inspect import isclass
from numpy.typing import NDArray

isinstance(NDArray, type) # True
isclass(NDArray) # True

issubclass(NDArray, int) # False - works
issubclass(int, BaseModel) # False - works

issubclass(NDArray, BaseModel) # Raises TypeError - doesn't work

Hence, this is some weird interaction between NDArray and pydantic’s BaseModel because they work as expected with other types.