Python class in Google Colab - python

I am trying to add a new Python class within an existing Collab project which is already working with a similar structure using classes within files within a sub file director (filedir). I have placed the new class, NewClassMethod, within a new_class.py file and put it into a directory. However, I am getting an error:
cannot import name 'NewClassMethod' from 'filedir1.filedir2'
There is a __init__.py file within that subdirectory of filedir2, but I haven't added anything to that. I am not sure if the error is related.
Thanks for any help. The full error is:
ImportError Traceback (most recent call last)
<ipython-input-11-f73c71e55f75> in <module>
----> 1 from filedir1.filedir2 import NewClassMethod
2 nn = NewClassMethod()
ImportError: cannot import name 'NewClassMethod' from 'cs231n.classifiers' (/content/drive/MyDrive/filedir1/filedir2/__init__.py)

Related

Why it can not find the package from subfolder [duplicate]

This question already has answers here:
Running unittest with typical test directory structure
(24 answers)
Closed 23 days ago.
I met a strange problem in python package. I have a python package named manchinetranslator in which I created a subfolder for unit tests as shown below.
manchinetranslator/translator.py
manchinetranslator/__init__.py
manchinetranslator/tests/tests.py
In translator.py, two functions are defined as:
def english_to_french(text):
...
def french_to_english(text):
...
The init.py is:
from . import translator
The tests.py contains unit tests of the two functions in translator.py and is as follows:
import unittest
from translator import english_to_french, french_to_english
class Test_english_to_french(unittest.TestCase):
...
class Test_french_to_english(unittest.TestCase):
...
But when running tests.py, it gives an error as follows:
Traceback (most recent call last):
File "C:\Python\manchinetranslator\tests\tests.py", line 3, in <module>
from manchinetranslator.translator import english_to_french, french_to_english
ModuleNotFoundError: No module named 'manchinetranslator'
However, when tests.py is put in the same folder as translator.py, it works fine. I guess it may need to set $PYTHONPATH, but I am not sure how to do it. So I need help with this problem.
You are trying to import from the parent directory, that won't work. tests.py cannot import from translator because it is inside it.
See this SO answer instead for what to do: https://stackoverflow.com/a/24266885/30581

ModuleNotFoundError: No module named 'data_management' in PyCharm

In github there are four py Data which I put on my PyCharm. When I run main.py I get this message:
/Users/Armut/Desktop/High_D/Coursera/bin/python /Users/Armut/Desktop/High_D/main.py
Traceback (most recent call last):
File "/Users/Armut/Desktop/High_D/main.py", line 6, in <module>
from data_management.read_csv import *
ModuleNotFoundError: No module named 'data_management'
Here is a screenshots:
Can someone help, what I am doing wrong or how can I fix it?
EDIT (Put folders):
/Users/Armut/Desktop/High_D/Coursera/bin/python /Users/Armut/Desktop/High_D/main.py
WARNING:root:Failed to import geometry msgs in rigid_transformations.py.
WARNING:root:Failed to import ros dependencies in rigid_transforms.py
WARNING:root:autolab_core not installed as catkin package, RigidTransform ros methods will be unavailable
Traceback (most recent call last):
File "/Users/Armut/Desktop/High_D/main.py", line 7, in <module>
from visualization.visualize_frame import VisualizationPlot
ModuleNotFoundError: No module named 'visualization.visualize_frame'
EDIT:
/Users/Armut/Desktop/High_D/Coursera/bin/python /Users/Armut/Desktop/High_D/src/main.py
Traceback (most recent call last):
File "/Users/Armut/Desktop/High_D/src/main.py", line 7, in <module>
from src.visualization.visualize_frame import VisualizationPlot
File "/Users/Armut/Desktop/High_D/src/visualization/visualize_frame.py", line 10, in <module>
from utils.plot_utils import DiscreteSlider
ModuleNotFoundError: No module named 'utils.plot_utils'
Edit (No errors, but I just get a blank picture):
Edit (I installed matplotlib 3.0.3 and got this):
The issue here is, that it is just a picture. If you can see there are buttons like "next". I should be able to click it so I can track it. But how does it work?
Do the following
from read_csv import *
import visualize_frame as vf
The reason why it was not working for you is because you were importing files that dont exist on your system. When you do from data_management.read_csv import *, what you are telling the Python interpreter to do is to search for a folder called data_management inside you're Coursera folder and get everything from read_csv.py.
This is the same case with visualize_frame. Since you have a flat directory structure, you dont need the folder names. You can directly import the .py files as is.
Another thing to note here is that I personally wouldn't do from read_csv import * because I will be flooding my namespace with a lot of things I probably wont use. I would rather use import read_csv as any_alias_you_like. This way I only fill my namespace with what I want by doing the following
x = any_alias_you_like.function_call()
The reason why I didn't do this with the main code solution is because I am not sure where all you are using read_csv functions and classes in your code and if that is not accounted for by prefxing the alias name properly, you will run into a multiple errors. So my advice is to identify all the funcutions/classes that you are using in read_csv.py and prefix them properly with an alias.
I also used the import statement for the visualize_frame differently. This is because, when you do a from import..., you are only partially initializing the module. However, a proper import visualize_frame will ensure that your entire module is initialized in one call and you can use everything it offers by simply prefixing the alias.
Read about the difference between from import and import... here.
Read about how Python searches for libraries here.

How to get Python relative imports right

I have a custom Python library ("common") that is being imported and used from several Python projects.
That central library has the following structure:
/common
/__init__.py
/wrapper.py
/util
/__init__.py
/misc.py
Our custom library resides in a central place /data/Development/Python, so in my Python projects I have an .env file in order to include our lib:
PYTHONPATH="/data/Development/Python"
That works fine, I can for example do something like:
from common.util import misc
However, now I want to make use of a class MyClass within common/wrapper.py from the code in common/util/misc.py. Thus I tried the following import in misc.py:
from ..wrapper import MyClass
But that leads to the following error:
Exception has occurred: ImportError
cannot import name 'MyClass'
Any ideas what I am doing wrong here?
PS: When I do an from .. import wrapper instead and then from code I use wrapper.MyClass, then it works fine. Does that make any sense?
It's finding wrapper, otherwise you'd get a different error:
>>> from wibble import myclass
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'wibble'
So it seems wrapper does not contain MyClass. Typo?
"However, now I want to make use of a class MyClass within common/wrapper.py from the code in common/util/misc.py. Thus I tried the following import in misc.py:"
If you do export PYTHONPATH=~/common
In order to import MyClass you will do:
from wrapper import MyClass
Because you have added common to your root folder, utils is already in your path since it is in you root folder.
Similarly, if you wanted to import from wrapper you would do from utils.misc import ThisClass since utils.misc is already in the root folder common

I am trying to call a function that I manually created in Python & saved in the lib directory. How can I do this?

I created a Binary Search Function in Python, and saved it as a .py file to the lib directory associated with Python Idle. How can I successfully call this function after importing it?
I receive an error when trying to call the function after adding parameters.
Error I receive:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
from lib import BinarySearch
ModuleNotFoundError: No module named 'lib'
EDIT: Using Windows 10, error I receive after correcting import statement:
import BinarySearch
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
BinarySearch()
TypeError: 'module' object is not callable
If you put BinarySearch.py in.../Pythonxy/Lib(to use the Windows name), useimport BinarySearch, just like you would useimport abcforLib/abc.pyand so on for other built-in modules in/Lib`.
[It would generally be better to call the file binary_search.py and reserve CamelCase names for classes. It would also be better to put your files in Lib/site-packages or in a directory in your user directory. But these are other issues.]
None of this has anything in particular to do with IDLE as such.
Edit: Now that you can import the module, you must call the function within the module. If the function is also called BinarySearch:
BinarySearch.BinarySearch()
or
from BinarySearch import BinarySearch # import the function from the module
BinarySearch()
I presume, though, that the function needs an argument or two.
[It would be less confusing if the module and function have different names, such as module binsearch (file binsearch.py) and function binary_search.]

Module not found when importing package

Even after googling, trying a million things etc, I just can't get package importing to work properly. I have a simple folder structure like this:
(main folder)
---------------
funktio (folder)---->| __init__.py |
main.py | tulosta.py |
country_data.py ---------------
Basically I'm trying to import tulosta.py into main.py. Tulosta.py has a function that prints certain stuff from country_data.py. So far the program works when I paste the contents of tulosta.py into main.py and scrap the import of tulosta.py from main.py (so the script reads from country_data properly). I'm doing a school assignment and it requires importing a module and a package. My problem is, if I try to
import funktio.tulosta
I only get
Traceback (most recent call last):
File "E:\Kouluhommelit\Script-programming\moduuliharkka\main.py", line 4, in <module>
tulosta.tulosta()
NameError: name 'tulosta' is not defined
and if I try to put "from tulosta import tulosta" into the init file, I get
Traceback (most recent call last):
File "E:\Kouluhommelit\Script-programming\moduuliharkka\main.py", line 1, in <module>
import funktio.tulosta
File "E:\Kouluhommelit\Script-programming\moduuliharkka\funktio\__init__.py", line 1, in <module>
from tulosta import tulosta
ModuleNotFoundError: No module named 'tulosta'
So basically whatever I try I get an error code. Here's the code from main.py:
import funktio.tulosta
import country_data
tulosta.tulosta()
and tulosta.py:
def tulosta():
for code in country_data.countrycodes:
print (country_data.codemap[code], ':\n\t','Head honcho:', country_data.countries[country_data.codemap[code]]['head honcho'],'\n\t','Population:', country_data.countries[country_data.codemap[code]]['population'],'million')
I'm really getting desperate after struggling with this for 4+ hours already. It seems like such a simple operation, but apparently it isn't. Please help. I'll provide more info if needed.
Here's the assignment:
Rearrange the code from previous exercises:
Make a folder called "moduuliharkka"
Make a python file called "country_data" where you put the lists and dicts from the exercise 15.
Then make a new folder inside the moduuliharkka-folder called "funktio" (tip: init)
Put the code from exercise 16. inside a function and save it as a .py file in the funktio-folder
Go back to your moduuliharkka-folder, make a main.py file where you import the country_data module and the funktio folder as a package
Call the function imported in the main.py script
You need to make one extra call in your main file. Currently, you have imported the file tulosta from funktio, however, you need to access the function/class/variable in that file. tulosta.tulosta() is not including the folder name, which is still needed
In main:
import funktio.tulosta
functio.tulosta.tulosta() #call the function in "tulosta" here
If you do want to call tulosta() as tulosta.tulosta(), import with an alias:
import funktio.tulosta as tulosta
tulosta.tulosta()

Categories