Error with class in python
Question: I've written some code that works when typed directly into the interpreter,
but fails when called.

Here's some code (there's a lot here to make it reproducible):

    
    
    import scikits.statsmodels.api as sm
    import pandas as pd
    data = sm.datasets.longley.load()
    df = pd.DataFrame(data.exog, columns=data.exog_name)
    y = data.endog
    df['intercept'] = 1.
    olsresult = sm.OLS(y, df).fit()
    olsresult2 = sm.OLS(y, df[['GNP', 'UNEMP', 'ARMED']]).fit()
    olsresult3 = sm.OLS(y, df[['GNP', 'POP', 'ARMED', 'YEAR']]).fit()
    models = [olsresult, olsresult2, olsresult3]
    
    class generateTable(object):
    
        def __init__(self, output, models, center='True', parens='se', var_names=None):
            self.output = output
            self.models = models
            self.center = center
            self.parens = parens
            self.var_names = var_names
    
        def createModel(self):
            results = []
            for model in self.models:
                params = dict(model.params)
                bse = dict(model.bse)
                pvals = dict(model.pvalues)
                results.append(dict((k, [params[k], bse[k], pvals[k]]) for k in sorted(params.iterkeys())))
    
            tempModel = {}
            for key in results[0]:
                tempModel[key] = [results[0][key]]
    
            for model in results[1:len(results)]:
                for key in model:
                    if key not in tempModel:
                        tempModel[key] = [['', '', '']]
    
            for i in range(1,len(results)):
                diff = set(tempModel) - set(results[i])
                for key in results[i]:
                    tempModel[key].append(results[i][key])
                for key in diff:
                    tempModel[key].append(['','',''])
    
    
            if self.var_names == None:
                self.inputModel = tempModel
            elif type(self.var_names) == list:
                replace = self.var_names
                newResults = []
                resultsList = sorted(tempModel.iteritems())
                for item in resultsList:
                    newVar = list(item)
                    newResults.append(newVar)
                for i in range(len(newResults)):
                    newResults[i][0] = replace[i]
                    self.inputModel = dict(newResults)
    

Whenever I try to run the script I receive an error `AttributeError:
'generateTable' object has no attribute 'model'`. IPython points out the line
`bse = dict(model.bse)`. Again, this works when I run it interactively (i.e.
chunk by chunk, no class), but when I import the file and try to run it I
receive the error.

**EDIT:**

1) How is it being created?

    
    
    import project
    
    a = project.generateTable('/path/to/test.tex', models, center='True', parens='se', var_names=None)
    a.createModel()
    

2) The whole traceback is:

    
    
    In [26]: a.createModel()
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    /path/to/project/<ipython-input-26-6774b6d1804c> in <module>()
    ----> 1 a.createModel()
    
    /path/to/project/project.py in createModel(self)
         39         for model in models:
         40             params = dict(model.params)
    ---> 41             bse = dict(model.bse)
         42             pvals = dict(model.pvalues)
         43             results.append(dict((k, [params[k], bse[k], pvals[k]]) for k in sorted(params.iterkeys())))
    

3) I'm going to try changing the var name `model` to something else.

4) Sorry about the syntax error. Thank you, asmeurer, for the fix.

**EDIT 2:**

3 above (changing the var name `model` to something else) didn't work.

## EDIT 3:

It works now. Here's the latest code:

    
    
    def __init__(self, output, models, center='True', parens='se', var_names=None):
        self.output = output
        self.models = models
        self.center = center
        self.parens = parens
        self.var_names = var_names
    
    def createModel(self):
        results = []
        for test_model in self.models:
            params = dict(test_model.params)
            bse = dict(test_model.bse)
            pvals = dict(test_model.pvalues)
            results.append(dict((k, [params[k], bse.get(k), pvals.get(k)]) for k in sorted(params.iterkeys())))
    

The only thing that's different is model in the for loop has been changed to
test_model. I tried that before and it didn't work, so I'm not quite sure how
it happend.

Thanks everyone for the help! And if anyone could point how why this change
got rid of that particular error message it'd be greatly appreciated. I'd like
to actually know what I was doing instead of just moving on and accepting it.


Answer: Whenever you see an error like `AttributeError: 'xxx' object has no attribute
'yyy'`, that can only mean one thing: you have an object of type `xxx` and you
are trying to access the attribute `.yyy` but the object doesn't have that
attribute. First rule of debugging: assume the error is telling the truth.

To put it in concrete terms, somewhere you are doing something like:

    
    
    a = project.generateTable()
    ...
    foo=a.model
    

When I look at the code you posted, I see nowhere where the attribute `model`
is defined for the class `generateTable`. Do you think you are setting it
somewhere? Either you aren't (which seems to be the case), or you are but you
are setting it at some point after you are first trying to access it.

