0

I have 2 .ipynb notebooks, A & B. I want to use some funcionts/class of A in B. Without running A.

Notebook "A":

class class_i_want_to_import_to_use:
    def __init__(self, x):
        print (x)
        
print ("Main that i don't want to run when importing ")

Notebook B

import import_ipynb
import A
b=A.class_i_want_to_import_to_use("run it in B notebook")

Out:

importing Jupyter notebook from A.ipynb
Main that i don't want to run when importing  #DONT WANT TO SEE THIS
run it in B notebook

is this possible or do i need to separate all my functions intoa notebook that doesn't run anything ?

Leo
  • 1,176
  • 1
  • 13
  • 33
  • 1
    Importing a file will always execute it as well - that's what makes the class definitions visible in the first place. It's up to you to ensure there are no undesirable side-effects when importing your file. Look into `__name__ == "__main__"` – Paul M. Nov 30 '20 at 10:08

1 Answers1

1

You need to use the __name__ == 'main' trick.

Check here for more info What does if __name__ == "__main__": do?

class class_i_want_to_import_to_use:
    def __init__(self, x):
        print (x)

#this block will not be executed by import
#but it will get executed when running the script
if __name__ == 'main':       
    print ("Main that i don't want to run when importing ")
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • Great, can I use __name__=="main": over multiple cell blocks? I dont want to lose readablility by putting all "main" into one notebook cell – Leo Nov 30 '20 at 10:15
  • You can add `if __name__ == 'main':` to each cell, if you need. The common practice is, however, to put all in one block at the end of the script. I suggest you to use the notebook to sketch your ideas, but then write a proper python file if you want to use it as a package. – alec_djinn Nov 30 '20 at 10:18