Can't find a variable that doesn't exist

Stoopid, stoopid me.

The symptoms

You have a Python script or package that is running perfectly. After you make some alterations, "all of a sudden" you can't run it because it can't find a variable or name:

AttributeError: 'module' object has no attribute 'foobar'

But if you search for that name, it doesn't exist anywhere in your code. WTF.

The solution(s)

There's two possible causes to this. Let's look at the kinder one first ...

Python source files are, of course, compiled into .pyc files for execution, which are created either on the same level as the source file (Python 2) or in special __pycache__ directories (Python 3). If a source file has been modified after the compiled file, then the compiled file is refreshed.

But sometimes odd things happen and the modification dates on files get out of sync, so that it looks like a source file is older than the compiled file. (I've seen this where I've copied files across systems with mismatching internal clocks for example. ) In this case, Python will not see any need to refresh the compiled file and so it will reflect an older version of your source. You'll start tearing your hair out and wondering where this imaginary code is coming.

The solution is to zap all your cache files. There's a useful Unix one-liner for doing this:

% find . -name "*.pyc" -type f -delete

Second possible solution is where you may be editing one version of the code, but Python is seeing the library of another Python version or installation. Pay attention to any paths shown in error messages and look elsewhere on this site for the PYTHONVERBOSE error article.

Finally, and embarrassingly, you may have done something like this: You wrote a statement to control symbol imports like:

__all__ = (
   'quux',
   'foo'
   'bar',
   'baz',
)

See the error? There's no comma after foo, so Python implicitly combines it with the strong on the following line to make foobar. Super-easy error to make and super-hard to see. Add the comma and you're fixed.