Import name conflicts

Ben Finney ben+python at benfinney.id.au
Tue Apr 18 18:45:50 EDT 2017


Tim Johnson <tim at akwebsoft.com> writes:

> Using python 2.7~

In Python 2, you should turn on the “default import is absolute” by
issuing the statement::

    from __future__ import absolute_import

as one of the first statements in each module.

When you migrate your code to PYthon 3, that will be the default
behaviour.

> The packages is called 'controllers' and has a submodule named 'imp'

To avoid the module named ‘imp’ in the standard library, your code
should import ‘imp’ using a relative import. See PEP 328
<URL:https://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports>.

So, you'd do::

    from . import imp

to import the ‘imp’ module relative to the current package.

> I do the following:
> >>> a = __import__('imp')

It is best to avoid calling dunder functions directly; they are
available for overriding the internals of language features, and
*invoking* one is best done by just using the corresponding language
feature.

Instead, use either the ‘import’ statement, or the ‘importlib’ standard
library module <URL:https://docs.python.org/2/library/importlib.html>,
specifically the ‘importlib.import_module’ function::

    import importlib

    a = importlib.import_module('.imp')

> Now, suppose a python upgrade provides a package called controllers or
> there's some great third-party package available called controllers.

You don't even have to imagine that far: there is already a standard
library module named ‘imp’, so you already have that problem to contend
with :-)

That is the distinction that led to “absolute” import versus “relative”
import.

> How do I access the 'global' controllers package?

* Enable “default import is absolute”, as described above.

* Issue a normal import statement: the absolute import search path will
  be used.

I hope that helps.

-- 
 \      “[I]t is impossible for anyone to begin to learn that which he |
  `\                thinks he already knows.” —Epictetus, _Discourses_ |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list