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 ?

1
  • 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__" Commented Nov 30, 2020 at 10:08

1 Answer 1

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 ")
Sign up to request clarification or add additional context in comments.

2 Comments

Great, can I use __name__=="main": over multiple cell blocks? I dont want to lose readablility by putting all "main" into one notebook cell
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.