Skip to content

Type hint of DataFrame(...dtype...) excludes numpy scalar types such as np.int8 #31872

@tomasssalles

Description

@tomasssalles

Code Sample

import pandas as pd
import numpy as np

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d, dtype=np.int8)

Problem description

The code sample above was taken straight from the API reference:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html

It results in a 'Type checker' inspection warning from PyCharm because np.int8 is not an instance of the expected type Union[str, np.dtype, "ExtensionDtype"]. Indeed, isinstance(np.int8, np.dtype) is false and the numpy documentation requires a conversion to get a data type object, such as np.dtype(np.int8).

Suggested solution

Change the type hint in DataFrame.init to

Union[str, np.dtype, np.generic, "ExtensionDtype"]

Less desirable solution

Change the API reference to use np.dtype(np.int8) instead. This would be a shame, because the current version is more elegant and works perfectly at runtime.

Expected Output

The code should not generate type checker warnings.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None
python : 3.6.9.final.0
python-bits : 64
OS : Linux
OS-release : 5.3.0-28-generic
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8
pandas : 1.0.0
numpy : 1.18.1
pytz : 2019.3
dateutil : 2.8.1
pip : 19.3.1
setuptools : 42.0.2
Cython : None
pytest : 5.3.5
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.1
IPython : 7.11.1
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : 3.1.2
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pytest : 5.3.5
pyxlsb : None
s3fs : None
scipy : 1.4.1
sqlalchemy : 1.3.13
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
numba : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Closing CandidateMay be closeable, needs more eyeballsDocsTypingtype annotations, mypy/pyright type checking

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions