0

I have a .ipynb file and want to only import certain functions from it to another .ipynb file.

if I use:

if __name__ == "__main__": 

would the script run what is under that if statement when I call:

%run file

For instance I have:

def someFuncToUseInOtherFile(df):
    x = do some process
    return x
def someFuncToUseInDifferentFile():
    y = do some process
    return y

#code not to run when script called from other file
if __name__ == "__main__":
    df = load dataframe
    x = ....
#other file
%run file

currently this runs the whole script but I just want to import the one function not both.

I have tried importing directly like a .py file, including using sys.path.append:

from file import someFuncToUseInOtherFile --> module not found error

import sys
sys.path.append(folder path)
from file import someFuncToUseInOtherFile --> module not found error

is there a way to get around this?

New contributor
user31922730 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1

1 Answer 1

1

Yes, as noted in comments, %run (and !) will run scripts as-is in a shell

At-face, you can either use a dedicated importer https://github.com/axil/import-ipynb or add additional guarding, like presence/absence of some flag beyond if __name__ == "__main__": .. more at Importing an ipynb file from another ipynb file?

However, if you're going to the trouble of creating dedicated functions at all, you're probably better served by simply putting them into a new simple .py library, which may greatly ease versioning them, and importing from that library in both notebooks!

Sign up to request clarification or add additional context in comments.

Comments

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.