Importing a library from (or near) a script with the same name raises “AttributeError: module has no attribute” or an ImportError or NameError

This happens because your local module named requests.py shadows the installed requests module you are trying to use. The current directory is prepended to sys.path, so the local name takes precedence over the installed name. An extra debugging tip when this comes up is to look at the Traceback carefully, and realize that the name … 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

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 do I extend a python module? Adding new functionality to the `python-twitter` package

A few ways. The easy way: Don’t extend the module, extend the classes. exttwitter.py import twitter class Api(twitter.Api): pass # override/add any functions here. Downside : Every class in twitter must be in exttwitter.py, even if it’s just a stub (as above) A harder (possibly un-pythonic) way: Import * from python-twitter into a module that … Read more

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