from module import * using __import__?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jul 5 00:51:49 EDT 2011


En Sat, 02 Jul 2011 16:52:11 -0300, Dan Stromberg <drsalists at gmail.com>  
escribió:

> Is there a decent way of running "from <variable> import *"?  Perhaps  
> using
> __import__?
>
> Does it mean using the copy module or adding an element to globals()
> somehow?
>
> Yes, I think I do have a good use for this: importing either pure python  
> or
> cython versions of a module into a single namespace that can provide the
> same interface (transparent to the caller), whether C extension modules  
> are
> viable in the current interpreter or not.  So you have a stub module that
> provides one or the other, depending on availability and suitability.

See pickle.py in Python 3 as an example: the slow (pure Python) code  
resides in pickle.py; the fast (C code) in _pickle.so (on Windows, a  
built-in module). Near the end of pickle.py, there is a line "from _pickle  
import *" which, if successful, overrides (replaces) any previous  
definitions; if not, the ImportError is trapped and the previously defined  
Python code remains valid.

Unlike the 2.x series, where you should decide to "import cPickle" or  
"import pickle" (or attempt both, cathcing the ImportError), here you only  
have to "import pickle" in your code; if the fast module is present, it is  
automatically loaded and used; else, the slow but compatible version is  
used. You don't even have to know that an alternative implementation  
exists.

-- 
Gabriel Genellina




More information about the Python-list mailing list