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

I have these two files:

def func_a():
    return object_a.method()

class ClassA:
    def __init__(self):

    def method(self):
        return "k"

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


import main


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\", line 16, in <module>
    import file_1
  File "C:\Users\Utente\PycharmProjects\pythonProject\", line 4, in <module>
  File "C:\Users\Utente\PycharmProjects\pythonProject\", 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 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

    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