D
D
Dinin042021-07-22 11:20:22
Python
Dinin04, 2021-07-22 11:20:22

How to import variables/functions correctly?

Hello everyone, I'm just learning python and ran into a problem with the logic of importing variables, functions, etc., I'll post a simple example that describes the issue

pesok.py

from autotesting.pesok import add
print(add)


pesok2.py

zxc = 1234567890
print(zxc)
add = 2


The idea is this: I run pesok.py, import the add variable from pesok2.py, then display it, but import runs the entire pesok2.py file and before add, it also outputs zxc, respectively.

How do I properly import the variable so that pesok.py only pulls the value of the add variable from pesok2.py?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2021-07-22
@Dinin04

The "correct" approach is:
pesok2.py

add = 2

if __name__ == "__main__":
    zxc = 1234567890
    print(zxc)

What is under the condition is not executed when imported, but when executed directly pesok2.py
ps remember: "pesok - plohaya zamena ovsu" (c) O'Henry

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question