Import functions from one ipynb file to another in vs code - python

I was trying to import functions from one notebook file to another in the most simplest way:
As you can see the files are in the same folder but I still get this error. Does anybody know how to resolve this?

For example, import funb() located in b.ipynb in a.ipynb.
install module: pip install ipynb
in a.ipynb:
import ipynb
from ipynb.fs.full.b import funb // ipynb.fs.full.<notebook_name>
funb()
See result:

You might try using the %run magic command.
You could store your functions in a sort of library notebook and use the following line to import them in your current notebook:
%run ./func_library_notebook.ipynb

Related

How do I import a module into my file in VS code while both of them are in the same folder?

I have two files, math_functions.py, and test.py under the same folder. I want to import math_functions into test.py but for some reason when I simply type it like below it won't work. I also tried 'Import Example3.math_functions' or when the Example3 folder had a space like so 'import Example_3.math_functions' it still throws an error. I forgot to show the error message but vs code tells me this 'import "math_functions" could not be resolved'. How can I import math_functions? I am running python 3.8
Try import the class or method directly
from math_functions import my_math_function
or if you want to import all of them at once, try
from math_functions import *
Okay so from what I found out, the code will still actually run and let you import the module regardless, I think this is just a visual studio thing throwing an error like this but this will still work regardless, now im curious as to whether there is anyway to get rid or ignore the error message. Thank you to those who have looked into it and tried to help
To import a file in the same folder, #shiny is right:
from math_functions import *
Referece: packages
About the warning that has no effect on code execution but wave underline displayed, if you're using pylint, you can add the following settings to your user settings.json file (opened with the File > Preferences > Settings command Ctrl+,):
"python.languageServer": "Jedi",
"python.linting.pylintArgs": ["--disable=W,C"],
Other Linter settings and detailed information you can refer to: linting-python-in-vscode.

Setting environment variables with Jupyter for doing `from module import function`

I have a python script called score.py that contains the following code:
def init():
print(os.getenv('hello')
I would like to test a method from this script with the following code in Jupyter, where the working directory contains score.py:
import os
os.environ['hello']='somevar'
from score import init
init()
Unfortunately, this code fails because 'hello' is not one of the variables that score.py can see. What am I doing wrong here?
My guess would be that this is some kernel related error. Have you also tried restructuring your code to the following and see if that works?
from score import init
import os
os.environ['hello']='somevar'
init()
If that doesnt work try the alternative way by setting an env variable in a jupyter notebook, just use a % magic commands, either %env or %set_env, e.g., %env MY_VAR=MY_VALUE or %env MY_VAR MY_VALUE. See here
In the worse case, just save it in a .env file and then load them in your script. This will most likely work.

Notebook import Jupyter

I am trying to import a class i created in one Jupyter notebook, to a different notebook and i get an error message saying the following:
from newclassattempt import MyClass
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-4-4337d8f762d7> in <module>
----> 1 from newclassattempt import MyClass
ModuleNotFoundError: No module named 'newclassattempt'
How can i get around this and import my class?
Please note that for the import to work we need the module to be a Python File, meaning with the extension .py.
The Jupyter Notebooks are not your plain python files and are thus not imported by normal python machinery
You can actually import a Jupyter Notebook using Hooks. A lot of it is detailed in the documentation. But I also found another method
In the thisnotebook.ipynb (the one you are working on), all you need to do is use these commands:
import import_ipynb
import newclassattempt
For this to work ensure that you install:
pip install import-ipynb
You can also use your from newclassattempt import MyClass
(The above was taken from this)
Update: I found a fully functional solution.
As mentioned in other comments, the class needs to be stored as a .py file in the same folder as the jupyter notebook. the following code then worked:
import newclassattempt
ob = newclassattempt.MyClass(1)
where newclassattempt is the name of the .py file, ob is the object created and MyClass is the class in the .py file. The reason my class couln't be imported is because I had not referenced the original file name

How to know the package or module name from import statement in Python?

I have a python file and the developer of that code has left the organization. When I run the code I get the following error.
import dataAnalysis as DV ModuleNotFoundError: No module named
'dataAnalysis'
I provide below the brief snippet of the python file "main.py" below.
import dataAnalysis as DV
def performCheck():
... other code
... other code
i = DV.addGraph( pathplus)
Here my question is , how to know the actual module or package name of "dataAnalysis" from the above import statement so that I can make "pip install ". However, I tried to install DataAnalysis module, still it does not work.
Is there any way to get the module or package name to install from the import statement in python ?
Go to console or terminal and run command pip install dataAnalysis. If permission denied, then make sure you have enough privilege to install a package.
Update:
In my opinion pip package DataAnalysis is a library that can be used for pre-processing a csv file. As per your given code, it looks like adding a graph so may be it could be a local package. Check dataAnalysis folder in your project with __init__.py file inside.

Why I am getting this error: object has no attribute 'astype'

I have defined a function myfunc inside a python file myfile. when i import this function from a jupyter notebook, it is showing the following error:
import numpy as np
import os
from scipy.misc import imread
import ast
from myfile import myfunc
.....
class_mask = np.equal(image, i)
class_mask = class_mask.astype(np.float32)
.....
AttributeError: 'NotImplementedType' object has no attribute 'astype'
However, whenever I have the myfile content in a cell and running inside the jupyter, it is working without any problem? What is the reason for this error?
Thanks
We can only import function from a python module/file. A Jupyter Notebook when you save have an extention of .pynb, that means its not actually a python module.
Just open your Notebook with a text editor, you probably see html like content. Which is not possible for a python module to contain.
You rather want to export the Jupyter Notebook as Python Module in the same directory from where you are trying to run your current program.
File -> Export as Python File
Once exported you can use it as just any other python module. Hope it helps!

Categories

Resources