4

When creating Python script on Jupyter, is it possible to call a function from another Python file?

When I try to call, it works on Terminal but does not work on Jupyter.

1
  • 1
    You can always import other .py files to access their functions. Commented Jun 29, 2018 at 12:56

3 Answers 3

3

For example, suppose I have a Person.py file and it is in the working directory of my current jupyter notebook. Furthermore, suppose it is simple and here it is

def get_rss(y, x):
    x = sm.add_constant(x)
    results=sm.OLS(y, x).fit()
    rss= (results.resid**2).sum()
    N=results.nobs
    K=results.df_model
    return rss, N, K, results

def myfunc(d):
    print("Hello my name is " + d)

When I try to call, it works on Terminal but does not work on Jupyter. When I try to call it as import Person, it works on Jupyter cell but I can not access the functions inside of it.

For example, if you tried writing this in Jupyter Notebook you might get this message after typing this Person.myfunc('ds')

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-60-63fdc0f35859> in <module>
----> 1 Person.myfunc('ds')

AttributeError: module 'Person' has no attribute 'myfunc'

My Advice

Restart your kernel and this should eliminate this problem. I hope this clarifies your question as well could be considered as an answer.

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

Comments

2

Just restart the kernel and it should work fine :)

1 Comment

lol, this was it
0

Firstly, if you're already working with other files, I recommend that you stop using jupyter and even terminal aswell.

You can use Pycharm instead.

If you were just learning, you could use jupyter but if you're already at that stage I recommend you to stick to Pycharm.

Pycharm is a nice IDE, where you can run the files directly on it, and has a lot more cool features.

Also, to use it in jupyter, just import the files you want:

import #whatever file you want

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.