Always can not import


(KyRie) #1

In the first part I encountered two problems: one is the ImportError: cannot, import name plots, another is ImportError: No module named vgg16, so that 7 lines of code I can run, I should download VGg or how to do, please help me, thank you


(Constantin) #2

OK, this is how you can organize the code for customized import (i.e. .py files with moduls you downloaded or wrote yourself and would like to import).
You have two options:

  1. Subdirectory of current project

  2. Your standard import path for your python installation.

  3. Subdirectory of current project
    Let’s say your project is in /home/user/awesome_project. Then make a subdir ~/awesome_project/utils.
    Place an (empty) file called __init__.py in it (using your favourite text editor). If this reminds you of the __init__ constructor in class definitions this is not a coincidence. Python treats imported modules the same way.
    In that same subdirectory ./utils you place (at least) a second file cool_shorthands.py with the class and function definitionas you’d like to include.
    In your notebook awesome.ipynb you include the following

from importlib import reload
import utils.cool_shorthands as cs; reload(cs)
from utils.cool_shorthands import *
```For explanation: reload lets you make changes to cool_shorthands.py while your notebook is open and just Shift+Enter one more time to import the changed modules. This is handy, because you will likely want to make changes while you develop. 
The second line imports your cool_shorthands into namespace cs. So you can go like ```cs.shortcut()``` in your notebook. 
The third line imports all modules directly, so you don't have to explicitely write ```cs.``` Instead you can go ```shortcut()``` 
Use this with care as there may be other imported modules with functions called the same name. 
Note: You can place another file, e.g. ```dask_iterator.py``` into ```./utils``` and import it using 
```import utils.dask_iterator as di```. You get the idea. 

2. Place it in your standard import path
The above was handy if you have a file for ONE project which you use to unclutter your notebook and move code out of the way. In case you'd like to re-use it in another project it is cumbersome to have to create the same subdirectory. Moreover, versioning could become a nightmare. So, you'd rather place it in the standard path. I am using anaconda3 and there you can find it using ```echo $PYTHONPATH``` on the command line. 
Likely you'll get something like ```/home/user/anaconda3/envs/my_dl_env/lib/python3.6/site-packages``` if you are running an environment called ```my_dl_env```. Customize as needed. Now, all you do is to create a subdir in this path e.g. ```./site_packages/utils```. 
Then you can import the same as described in 1.

This way you can unclutter your notebooks really well and get your own code base organized.