Home > database >  How can I call a function from another file which contains an object defined in the main_file?
How can I call a function from another file which contains an object defined in the main_file?

Time:05-05

I have these two files:
main.py

def func_a():
    return object_a.method()


class ClassA:
    def __init__(self):
        pass

    def method(self):
        return "k"


if __name__ == '__main__':
    object_a = ClassA()
    print(func_a())
    import file_1

and file_1.py

import main


print(main.func_a())

when I call func_a in main, I do not get any errors, but when file_1 calls func_a, i get these errors:

Traceback (most recent call last):
  File "C:\Users\Utente\PycharmProjects\pythonProject\main.py", line 16, in <module>
    import file_1
  File "C:\Users\Utente\PycharmProjects\pythonProject\file_1.py", line 4, in <module>
    print(main.func_a())
  File "C:\Users\Utente\PycharmProjects\pythonProject\main.py", line 2, in func_a
    return object_a.method()
NameError: name 'object_a' is not defined. 

CodePudding user response:

since __name__ != "__main__", object_a is never created in main.py. If you remove object_a = ClassA() from the if then it will run fine.

CodePudding user response:

It is confusing, because you are expecting that having run the line: object_a = ClassA() that object_a will be attached to the main module.

You could try adding this as your first line of main.py:

print('top of main', __name__)

You will see this line execute twice as you are expecting, but with different outcomes.

CodePudding user response:

Thanks for your answers. I did not write the question well: I would like to create object_a once by starting main.py, and have the object_a methods used by calling func_a from other files (which will be executed by main.py)

  • Related