1

If I want to explain the problem in a simplified way, I have two A.ipynb and B.ipynb files. In file B I call a function from outside of __main__ in file A but I can not access it and give NameError: name 'do' is not defined error.
File A.ipynb:

if __name__ == "__main__":
    def do(value):
        print(value)

def func(value):
    do(value)

File B.ipynb:

import import_ipynb
from A import *

func('some text')

I want to see 'some text' as output in console when file B executed. I think Something like (in any way that can be done):

def func(value):
    main().do(value)

can solve problem.

4
  • 2
    You only define do if you run the A-file. If you run the B-file, do will not be defined. That's the meaning of if __name__ == "__main__". Commented Nov 23, 2020 at 20:26
  • So what are you asking? You defined something in the main function in file A, meaning it's only defined when file A's main function runs - meaning if you import file A from file B, that thing won't be defined, since importing a file doesn't run its main function. What are you confused on? When main runs? Commented Nov 23, 2020 at 20:32
  • Okay, so what is your question? How is the code supposed to be used, and what is supposed to happen when it runs? Commented Nov 23, 2020 at 20:34
  • The if statement that checks the value of __name__ is not an entry point to the script, like the function named main in C or Java. All Python programs start at the top and execute statements in order. Are you sure you even want such an if statement? Commented Nov 23, 2020 at 20:38

1 Answer 1

1

I think you're focusing on func() being missing/undefined when it's actually that do() is missing or undefined.

Your file B is able to find the definition for func() but then it tries to call do() which has not been defined, because the if __name__ clause prevented it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.