Locane Locane - 11 months ago 55
Python Question

How to import custom module the same way as pip-installed modules?

I feel really dumb asking this question, but it's a quirk of python I've put up with for awhile now that I finally want to fix.

On CentOS 7, given that I have "roflmao.py" and "__init__.py" in the directory:


Why is it that when I'm using the python interpreter (and not in the directory containing roflmao.py), I must type:

from roflmao import roflmao

Instead of simply:

import roflmao

To gain access to "roflmao.py"'s functions and variables? I can import re, collections, requests, or any PIP-installed module just fine, but not my own custom one.

How can I set things up to accomplish this?

Answer Source

Put from roflmao import * into __init__.py.

If you do this, then you don't really need to use roflmao.py. Because it would then be pointless to do from roflmao import roflmao. So it's best to just put the code from roflmao.py into __init__.py.