Skip to content

Attribute Existence Ambiguity #3787

Open

Description

@jbrockmendel

Moving part of the conversation from #3570

moving away from self.__dict__.update(...) ?

Why? What would be the problem? What would be the alternative?
I don't have a strong opinion but it worked well and don't remember ever having problems with it. We use it a lot. So any moving away would depend on a better alternative.
self.__dict__.update(mlefit.__dict__) looks like a simple way to copy over attributes.

and/or setattr

no idea, I didn't know or remember that we use it. So I don't have currently an opinion.
We use getattr with a default if the attr doesn't exist pretty often.

I count 15 appearances of __dict__.update and ~50 setattr, excluding results and tests modules.

What would be the problem?

The problem is that it is difficult to reason about what attributes exist where.

Take for instance ModelData. Inside __init__ it runs either self.__dict__.update(arrays) or self.__dict__.update(kwargs) to attach essentially everything (aside from exog and endog I'm not even sure what else is in here or why). Then in Model._handle_data many of those kwargs then get popped off of data.__dict__ to get attached to model instead. The problem is that reasoning about what attributes exist where is difficult and shouldn't be.

self.__dict__.update(mlefit.__dict__) in GenericLikelihoodModelResults I'll live with as it is specifically intended to be user-obscure magic. DiscreteResults I'd like to change to call super(DiscreteResults, self).__init__ and avoid the self.__dict__.update, but that is a much lower priority than the ModelData/Model case.

The alternative I would advocate:

ModelData - Explicitly specify the attributes that are important (exog, endog, ??), and any other array-like objects or kwargs go into dictionaries like data._arrays and data._init_kwargs. Then we know exactly what attributes exist, and exactly where to find any other auxiliary objects.

Model - Explicitly specify the parts of ModelData that should be copied over. Anything else either goes into an auxiliary dictionary or is accessed via model.data.foo.

We use getattr with a default if the attr doesn't exist pretty often.

If there are common attributes like this, let's initialize them to None from the get-go (in __new__ if we have no other choice) and avoid any ambiguity as to what exists.

Activity

  1. josef-pkt commented on Jun 26, 2017

    @josef-pkt
    Member

    Note, all the data handling was Skipper's work and I'm only familiar enough to be able to bug hunt in there, and to have a rough overview about what the moving parts are.

    Some of those things are intentionally vague and blanket copies or operations because those parts should work with any model without developers having to dig into the data handling part. E.g. only endog and exog are required by almost all models (exog can be None), but there are a large number of extra arrays that specific models need in specific cases, e.g. we are adding 3 kinds of weights to GLM, MixedLM requires some extras, Zero-Inflated is a two part model like some others with two exog. instruments in instrumental variables models are extra, offset and exposure in some models, offset should be more general, ...

    So these unspecific ways of handling data with getattr/setattr and self.__dict__.update are cheap ways of being "generic". There is no generic way to know which attributes are, should or can be there. Only the model.__init__ specify that.

    That's the flexibility and benchmark that any refactoring will need to address/handle. As I argued in the remove_data case, I'm fine with or in favor of registering "keys", but it needs to work without being ugly, or without increasing the work and complexity for developers of new models by much. (The assumption is that data handling "just works", and as a regular developer I don't need to care about those details.)

    (A bit related: missing value handling also automatically checks every nobs array for nans to find the common non-missing rows.)

    Another related part is that I started the model.__init_keys or similar to be able to recreate models with the original "extras" but that includes all keywords irrespective of shape or whether they are data. We could only get those arguments generically with inspect which I don't like at all in regular code. (i.e. usage of inspect is banned along regular execution paths.)

  2. jbrockmendel commented on Jun 29, 2017

    @jbrockmendel
    ContributorAuthor

    I've now gone over base.data in some detail. The topics to consider going forward can be broken down into three largely orthogonal pieces.

    1. Cleanup that doesn't impact any of the underlying logic. There is a lot of unnecessary complexity, particularly in handle_missing. A made up example:
    for ...
        names += ('foo',)
        vals += [value]
    
    combined = dict(zip(names, vals))
    or_even = dict(zip(names, list(map(func, vals))))
    

    can be pythonicized to:

    for ...
        combined['foo'] = value
        or_even['foo'] = func(value)
    
    1. Namespace decisions that affect the logic in non-user-facing ways.

    a) __dict__.update can be avoided by appending a _arrays dictionary to ModelData. Then model.Model._handle_data can pop from data._arrays instead of data.__dict__. AND can add those popped keys to model._data_attr (this is probably the most obvious "win" of this post).

    b) If we get rid of the __dict__.update inside of ModelData.__init__, then the only (see b)i)) other currently-ambiguous attribute is predict_dates, which is referenced in data but set externally from tsa_model.TimeSeriesModel._get_prediction_index. That is a rabbit hole I don't want to get into, so for now will advocate just initializing predict_dates to None at the top of ModelData.__init__.
    b) i) TimeSeriesModel._get_prediction_index also sets data.predict_start and data.predict_end, neither of which ever appears to be used. Unless there is some plan to change that, it might be better not to set these at all.

    c) Evaluating (cheap) label-related cache_XYZ attributes at the end of ModelData.__init__ to ensure that these name attributes exist when it comes time to do wrapping.

    1. API-related decisions:

    a) A richer wrap_output API to handle corner cases. One option would be to allow how to be a function so the user can catch special cases downstream.

    b) The NaN handling is all front-end while the names/labels/wrapping is all back-end. The two responsibilities could be more or less separated, which would basically be a move towards the NoDataMixin you suggested in #3570.

    c) NaN handling currently drops all NaN rows, which can be problematic for tsa models (and is why statespace circumvents it). For many non-tsa models, users will want to use dummies for NaNs or do some form of imputation. If we want to support these options down the road, data.handle_data would be the right place for that. Emphasis on "down the road".

  3. kshedden commented on Jul 3, 2017

    @kshedden
    Contributor
  4. added this to the 0.10 milestone on Oct 7, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions