Answer the question
In order to leave comments, you need to log in
Python. Area of visibility. How to access variable from __main__ section?
The situation seems to be the simplest, but nothing happens. Help me please.
main.py
b = 2
if __name__ == '__main__':
a = 1
print(a, b)
>>> 1 2
import main
print(main.a)
print(main.b)
>>> print(main.a)
>>> AttributeError: module 'main' has no attribute 'a'
Answer the question
In order to leave comments, you need to log in
Scope of view has nothing to do with it.
If a module is not run directly, but is imported from another module, then its __name__ attribute will not be equal to "__main__", and everything that goes inside the condition will simply not be executed, and the 'a' variable will not be created at all.
Actually, the if __name__ == '__main__' construct is used when they want some logic to be executed ONLY if the module is launched directly, and not imported.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question