Skip to content

Instantly share code, notes, and snippets.

@plant99
Last active August 16, 2020 19:17
Show Gist options
  • Save plant99/9fee5dbe73f25d4da9c7fb956a36b889 to your computer and use it in GitHub Desktop.
Save plant99/9fee5dbe73f25d4da9c7fb956a36b889 to your computer and use it in GitHub Desktop.

The easiest way to get an ImportError in Python is to install Python and open a console, type the following.

from sys import ham
---------------------------------------------------------------------------

ImportError                               Traceback (most recent call last)

<ipython-input-7-cd4f03518964> in <module>
----> 1 from sys import ham


ImportError: cannot import name 'ham' from 'sys' (unknown location)

Similarly, the easiest way to get a ModuleNotFoundError is to do the following in console.

import spam
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

<ipython-input-9-bdb680daeb9f> in <module>
----> 1 import spam


ModuleNotFoundError: No module named 'spam'

A better exercise for individuals already writing some Python would be to create a directory spam and two subdirectories ham and eggs

example-app/

├── eggs

   └── egg_func.py

└── ham.py

# ham.py
x = 3
y = 4
# eggs/egg_func.py
from ham import x

def print_stuff():
    print("although it's defined in eggs, i dont consider to be the real x", x)

If you execute example-app/eggs/egg_func.py, the console would output the following.


Traceback (most recent call last):
  File "example-app/eggs/egg_func.py", line 1, in <module>
    from ham import x
ImportError: No module named ham

It's because $PYTHONPATH couldn't find module 'ham', root directory /.../example-app/ . If you add this directory to $PYTHONPATH, they work.

Let's discuss the what(s), why(s), and dig much more deeper during the talk :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment