Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix type annotations in pandas.core.dtypes #26029

Merged
merged 4 commits into from
Apr 12, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,6 @@ ignore_errors=True
[mypy-pandas.core.config_init]
ignore_errors=True

[mypy-pandas.core.dtypes.dtypes]
ignore_errors=True

[mypy-pandas.core.dtypes.missing]
ignore_errors=True

[mypy-pandas.core.frame]
ignore_errors=True

Expand Down
7 changes: 3 additions & 4 deletions pandas/core/dtypes/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Extend pandas with custom array types"""
from typing import List, Optional, Type
from typing import List, Optional, Tuple, Type

import numpy as np

Expand All @@ -24,7 +24,7 @@ class _DtypeOpsMixin(object):
# of the NA value, not the physical NA vaalue for storage.
# e.g. for JSONArray, this is an empty dictionary.
na_value = np.nan
_metadata = ()
_metadata = () # type: Tuple[str, ...]

def __eq__(self, other):
"""Check whether 'other' is equal to self.
Expand Down Expand Up @@ -219,8 +219,7 @@ def type(self) -> Type:
raise AbstractMethodError(self)

@property
def kind(self):
# type () -> str
def kind(self) -> str:
"""
A character code (one of 'biufcmMOSUV'), default 'O'

Expand Down
40 changes: 24 additions & 16 deletions pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
""" define extension dtypes """
import builtins
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I found some more information on this error:

python/mypy#1775

The suggested approach there is to alias the type rather than import builtins.

However, this comment by Guido might also be of importance:

python/mypy#1775 (comment)

His example cites a method where a subsequent annotation mangles a method with the name of bytes with the builtin. I imagine this is the same with the static variable (if you could confirm would be great) so we would have to be pretty careful when typing this module with str and type to avoid nuanced errors

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can confirm that within the body of the classes, the class variables str and type are clobbering the builtins. So, e.g, in the class itself (but not in its methods, which each have their own scope) isintance("asdf", str) will throw a TypeError because the second argument isn't a type or tuple of types. Likewise, isinstance(int, type) in that location will throw the same error.

Within the methods, things work normally, see e.g.,

if isinstance(dtype, str) and dtype == 'category':

import re
from typing import Any, Dict, Optional, Tuple, Type
import warnings

import numpy as np
Expand Down Expand Up @@ -104,17 +106,23 @@ class PandasExtensionDtype(_DtypeOpsMixin):

THIS IS NOT A REAL NUMPY DTYPE
"""
type = None
type = None # type: Any
gwrome marked this conversation as resolved.
Show resolved Hide resolved
kind = None # type: Any
"""
jreback marked this conversation as resolved.
Show resolved Hide resolved
The Any type annotations above are here only because mypy seems to have a
problem dealing with with multiple inheritance from PandasExtensionDtype
and ExtensionDtype's @properties in the subclasses below. Those subclasses
are explicitly typed, as appropriate.
"""
subdtype = None
kind = None
str = None
str = None # type: Optional[builtins.str]
num = 100
shape = tuple()
shape = tuple() # type: Tuple[int, ...]
itemsize = 8
base = None
isbuiltin = 0
isnative = 0
_cache = {}
_cache = {} # type: Dict[builtins.str, object]
gwrome marked this conversation as resolved.
Show resolved Hide resolved

def __unicode__(self):
return self.name
Expand Down Expand Up @@ -217,12 +225,12 @@ class CategoricalDtype(PandasExtensionDtype, ExtensionDtype):
"""
# TODO: Document public vs. private API
name = 'category'
type = CategoricalDtypeType
kind = 'O'
type = CategoricalDtypeType # type: Type[CategoricalDtypeType]
kind = 'O' # type: builtins.str
str = '|O08'
base = np.dtype('O')
_metadata = ('categories', 'ordered')
_cache = {}
_cache = {} # type: Dict[builtins.str, object]

def __init__(self, categories=None, ordered=None):
self._finalize(categories, ordered, fastpath=False)
Expand Down Expand Up @@ -584,15 +592,15 @@ class DatetimeTZDtype(PandasExtensionDtype, ExtensionDtype):
THIS IS NOT A REAL NUMPY DTYPE, but essentially a sub-class of
np.datetime64[ns]
"""
type = Timestamp
kind = 'M'
type = Timestamp # type: Type[Timestamp]
gwrome marked this conversation as resolved.
Show resolved Hide resolved
kind = 'M' # type: builtins.str
gwrome marked this conversation as resolved.
Show resolved Hide resolved
str = '|M8[ns]'
num = 101
base = np.dtype('M8[ns]')
na_value = NaT
_metadata = ('unit', 'tz')
_match = re.compile(r"(datetime64|M8)\[(?P<unit>.+), (?P<tz>.+)\]")
_cache = {}
_cache = {} # type: Dict[builtins.str, object]

def __init__(self, unit="ns", tz=None):
"""
Expand Down Expand Up @@ -736,14 +744,14 @@ class PeriodDtype(ExtensionDtype, PandasExtensionDtype):

THIS IS NOT A REAL NUMPY DTYPE, but essentially a sub-class of np.int64.
"""
type = Period
kind = 'O'
type = Period # type: Type[Period]
kind = 'O' # type: builtins.str
str = '|O08'
base = np.dtype('O')
num = 102
_metadata = ('freq',)
_match = re.compile(r"(P|p)eriod\[(?P<freq>.+)\]")
_cache = {}
_cache = {} # type: Dict[builtins.str, object]

def __new__(cls, freq=None):
"""
Expand Down Expand Up @@ -860,13 +868,13 @@ class IntervalDtype(PandasExtensionDtype, ExtensionDtype):
THIS IS NOT A REAL NUMPY DTYPE
"""
name = 'interval'
kind = None
kind = None # type: Optional[builtins.str]
str = '|O08'
base = np.dtype('O')
num = 103
_metadata = ('subtype',)
_match = re.compile(r"(I|i)nterval\[(?P<subtype>.+)\]")
_cache = {}
_cache = {} # type: Dict[builtins.str, object]

def __new__(cls, subtype=None):
"""
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/dtypes/missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"""
import numpy as np

from pandas._libs import lib, missing as libmissing
from pandas._libs import lib
import pandas._libs.missing as libmissing
WillAyd marked this conversation as resolved.
Show resolved Hide resolved
from pandas._libs.tslibs import NaT, iNaT

from .common import (
Expand Down