The following principles should inspire refactoring of indexing code. I (toobaz) claim that they will result on cleaner, simpler, and more performant code.
-
Label indexing must never involve looking in an axis twice for the same label(s). This implies that any validation step must either:
i) limit validation to general features (e.g. dtype/structure of the key/index), or
ii) reuse the result for the actual indexing.
-
With the possible exception of
.ix, indexers must never rely on an explicit call to other indexers. For instance, it is OK to have some internal method of.loccall some internal method of__getitem__(or of their common base class), but never in the code flow of.locshouldthe_obj[something]appear. -
Execution of positional indexing must never involve labels (as currently, sadly, happens). That is, the code flow of a getter call (or a setter call in which the right hand side is non-indexed) to
.ilocshould never involve the axes of the object in any way. -
Indexing must never involve accessing/modifying values (i.e., act on
._dataor.values) more than once. The following steps must hence be clearly decoupled:i) find positions we need to access/modify on each axis
ii) (if we are accessing) derive the type of object we need to return (dimensionality)
iii) actually access/modify the values
iv) (if we are accessing) construct the return object
-
As a corollary to the decoupling between 4.i and 4.iii, any code which deals on how data is stored (including any combination of handling multiple dtypes, and sparse storage, categoricals, third-party types) must be independent from code that deals with identifying affected rows/columns, and take place only once step 4.i is completed.
i) In particular, such code should most probably not live in
pandas/core/indexing.pyii) ... and must not depend in any way on the type(s) of axes (e.g. no
MultiIndexspecial cases) -
As a corollary to point 1.i,
Index(sub)classes must provide separate methods for any desired validity check of label(s) which does not involve actual lookup, on the one side, and for any required conversion/adaptation/lookup of label(s), on the other. -
Use of trial and error should be limited, and anyway restricted to catch only exceptions which are actually expected (typically
KeyError).- In particular, code should never (intentionally) raise new exceptions in the
exceptportion of atry... exception
- In particular, code should never (intentionally) raise new exceptions in the
-
Any code portion which is not specific to setters and getters must be shared, and when small differences in behavior are expected (e.g. setting with
.locraises for missing labels, getting still doesn't), they can be managed with a specific parameter.