Search code examples
pythonimportattributeerror

Importing module, AttributeError


I'm trying to import a module to use a couple of methods it has, and for some reason all of a sudden I get the error:

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

Of course I have a method getFoobar in the module I'm importing. I'm using it in other files with no problem. This never happened before.

I've already tried to delete all the .pyc files, I've checked that I have a __init__.py in the same folder, and there are no mutual imports going on.

I've searched SO and Google and no solution fixed the problem for me. Any ideas on what could be going on? What else can I try?

Thanks!


Solution

  • Are you trying to access a free module-level function, or a method? It makes a major difference. If you have something like this:

    class foo:
        def bar1():
            pass
    def bar2():
        pass
    

    saved in a file "foo.py", then you need to do different things to call each one, like this:

    import foo
    f = foo.foo()
    f.bar1()
    foo.bar2()
    

    As you can see, you can directly access bar2 from the foo module, since it is outside of class foo, but you need to declare an instance of class foo to call bar1. I'm assuming you were just trying to call bar1 from the foo module, as that's a common beginners mistake, especially if you switched over from Java.