-1

I have these two modules:

foo.py
bar.py

In foo.py I have a function fn() declared and a print('test'), outside of fn() context.

At the top of bar.by, I do:

from foo import fn

I can call fn, but I also print 'test', which I don't want.


Why? How can I import only what is explicitly imported from another module?

8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198
  • 1
    use ```if __name__ == "__main__": ``` at start of ```foo``` and all code after to be inside it to prevent python from running foo module when imported. Your way prevent python from importing extra names into your namespace – KMG Oct 05 '20 at 00:17
  • Please provide the expected [MRE](https://stackoverflow.com/help/minimal-reproducible-example). We should be able to paste a single block of your code into file, run it, and reproduce your problem. – Prune Oct 05 '20 at 00:42

2 Answers2

2

You should restructure foo.py to be:

def fn():
   # statements


if __name__ == "__main__":
    print('test')

Now, when you import fn from foo in your other script, the print function will not be run.

Rex Parsons
  • 199
  • 10
0

The way python works, importing will execute the target python file first. When you use from X import Y it still executes the file, but will only include the specific Y items into your namespace.

You can exclude print("test") by first checking if __name__ == "__main__" to see if the current file is being executed or just being used as an import.

Locke
  • 7,626
  • 2
  • 21
  • 41