R
R
RUNAMAN2018-02-08 19:37:03
Python
RUNAMAN, 2018-02-08 19:37:03

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)

If we run from the main.py module, we get, this is understandable
>>> 1 2
But if we try to call the variable a from the add.py module
add.py
import main

print(main.a)
print(main.b)

We get an error
>>> print(main.a)
>>> AttributeError: module 'main' has no attribute 'a'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimonchik, 2018-02-08
@dimonchik2013

you don't declare "a", where does it come from?

A
Alexander, 2018-02-08
@fireSparrow

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 question

Ask a Question

731 491 924 answers to any question