Python: ‘Private’ module in a package

I prefix private modules with an underscore to communicate the intent to the user. In your case, this would be mypack._mod_b This is in the same spirit (but not completely analogous to) the PEP8 recommendation to name C-extension modules with a leading underscore when it’s wrapped by a Python module; i.e., _socket and socket.

How can I import a module dynamically given the full path?

For Python 3.5+ use (docs): import importlib.util import sys spec = importlib.util.spec_from_file_location(“module.name”, “/path/to/file.py”) foo = importlib.util.module_from_spec(spec) sys.modules[“module.name”] = foo spec.loader.exec_module(foo) foo.MyClass() For Python 3.3 and 3.4 use: from importlib.machinery import SourceFileLoader foo = SourceFileLoader(“module.name”, “/path/to/file.py”).load_module() foo.MyClass() (Although this has been deprecated in Python 3.4.) For Python 2 use: import imp foo = imp.load_source(‘module.name’, ‘/path/to/file.py’) foo.MyClass() … Read more

What does if __name__ == “__main__”: do in Python?

Short Answer It’s boilerplate code that protects users from accidentally invoking the script when they didn’t intend to. Here are some common problems when the guard is omitted from a script: If you import the guardless script in another script (e.g. import my_script_without_a_name_eq_main_guard), then the latter script will trigger the former to run at import … Read more

Can’t install mysql-python (newer versions) in Windows

I solved it myself. I use the wheel installer from http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python. There are two wheel packages there. The amd64 one refuses to install on my platform (Windows) but the other one works just fine. I mean the file with this name: MySQL_python-1.2.5-cp27-none-win32.whl Then install it by running this below command in the same folder with … Read more

How does python find a module file if the import statement only contains the filename?

http://docs.python.org/3/tutorial/modules.html#the-module-search-path 6.1.2. The Module Search Path When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations: The directory containing the … Read more