-1

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?

Tazerface
  • 3
  • 3
  • 1
    Are you aware of the [scoping rules](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules)? Python is *lexically* scoped, functions only see what is in their *defining* scope not their *using* scope. – MisterMiyagi Feb 08 '22 at 10:51

1 Answers1

0

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.

Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50