-1

For example take a.py

stringcheese = "hi"
print("I don't want this printed")

and now b.py:

from a import stringcheese
print(stringcheese)

The output is:

I don't want this printed
hi

How can I just import stringcheese without executing a.py's code?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

3

You can't. The top-level code for a module must be executed for the module to load in the first place.

Only put executable statements in the top-level of your module that you are fine with being executed on import.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
-1

POSUM SHREDER, you can use if __name__ == '__main__' construction to hide unwated executables from import, they still wll be executed if you call python a.py.

a.py

stringcheese = "hi"
if __name__ == '__main__' :
    print("I don't want this printed") 

main.py

from a import stringcheese
print(stringcheese)

for more details please read What does if __name__ == "__main__": do?

Community
  • 1
  • 1
Trigremm
  • 61
  • 7
  • Your answer is right but explain your answer a little don't just dump code, so others and the OP can learn – danidee Feb 16 '16 at 09:40
  • @Trigremm Your answer could still use more love, such as quickly explaining what `__name__` is in addition to the link. I'm +1-ing your answer for the editing effort though, it's a significant improvement over your initial version. Welcome to Stack Overflow. – spectras Feb 16 '16 at 10:02