kilojoules kilojoules - 2 months ago 13
Python Question

metaheuristic-algorithms-python throws import error but is definitely installed (this package is only tested in python3 and I'm using python 2.7)

I can't import the metaheuristic-algorithms-python library after installing it in python. Why isn't this working? It is installed in my site-packages but it cannot be imported. The docs say this is only tested for python3. Looking through the code, it looks like this should work in python 2.7. What's going on?

$ virtualenv working
$ . working/bin/activate
$ pip install metaheuristic-algorithms-python
$ ls working/lib/python2.7/site-packages/metaheuristic_algorithms
base_algorithm.py command_line.pyc function_wrappers harmony_search.py simplified_particle_swarm_optimization.pyc version.py
base_algorithm.pyc firefly_algorithm.py genetic_algorithm.py harmony_search.pyc simulated_annealing.py version.pyc
command_line.py firefly_algorithm.pyc genetic_algorithm.pyc simplified_particle_swarm_optimization.py simulated_annealing.pyc
$ working/bin/python -c "import metaheuristic_algorithms"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named metaheuristic_algorithms

Answer

You know how they said they don't support Python 2? Well, this is one of those things that works on Python 3 and not Python 2. Specifically, this package has no __init__.py.

On Python 3, a package with no __init__.py is a namespace package, a kind of package that works slightly differently from regular packages. On Python 2, a folder with no __init__.py isn't even a package. You can't import this thing, because Python doesn't consider it a package.