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

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. 

2 answers

  • answered 2022-05-04 10:44 CasualScience

    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.

  • answered 2022-05-04 10:55 quamrana

    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.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum