Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call function from another Python file on Jupyter?

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.

like image 421
Nontawat Pattanajak Avatar asked Oct 31 '25 04:10

Nontawat Pattanajak


1 Answers

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.

like image 181
rsc05 Avatar answered Nov 02 '25 18:11

rsc05



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!