Search code examples
pythonclassimportmodulenameerror

Class instance can't see a function it refers to


I have this module containing a class definition and instantiation, like so:

class TestClass:
    def __init__(self, name):
        self.name = name
    def func(self, count):
        count = test_func(count)
        return count

my_inst = TestClass('my_inst')

Note that TestClass.func refers to a function (test_func) that is not in the module. Then, I open a notebook where that function is defined and import the TestClass and its instance, my_inst. The count variable is also defined in the notebook, so the code in it looks as follows:

from test_module import *

count = 0

def test_func(count):
    count += 1
    return count

Then, I try to run the my_inst.func(count) method...

for _ in range(10):
    count = my_inst.func(count)

...and get a NameError: name 'test_func' is not defined.

What seems to be the problem here? Why doesn't the class instance see the test_func in the notebook? How can I make it see it?


Solution

  • You need to import test_func within the file in which TestClass is defined. You're doing the opposite (i.e., you're importing TestClass within the file in which test_func is defined), which is wrong and will never work.

    File test_function.py:

    count = 0
    
    def test_func(count):
        count += 1
        return count
    

    File test_class.py:

    from test_function import test_func
    
    class TestClass:
        def __init__(self, name):
            self.name = name
        def func(self, count):
            count = test_func(count)
            return count
    
    my_inst = TestClass('my_inst')
    

    Now you can import everything you need in your notebook.