0

When I import a function from a Python file, I don't want it to be executed whole. I only want the function to be imported. Currently when I import the function, the a.py file gets executed.

a.py

def func():
    print("inside func")


print("outside func")

b.py

from a import func

func()
print("in B")

Output

outside func
inside func
in B

Expected/wanted

inside func
in B
jkdev
  • 11,360
  • 15
  • 54
  • 77
WhySoSerious
  • 185
  • 1
  • 19
  • 1
    Maybe see here: [Maybe see here](https://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it) – Moritz Sep 13 '19 at 13:38
  • When you import a module, all it's code gets executed. Instead, you should design your modules to be used as a library. – juanpa.arrivillaga Sep 13 '19 at 16:43

1 Answers1

1

Wrap the print call in a.py in a def main():, then add

if __name__ == '__main__':
        main()

to the bottom of a.py. This will prevent the print from being called unless a.py is run directly.

Jason Stein
  • 714
  • 3
  • 10