Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd like to offer my version, which is a combination of Boaz Yaniv's and Omnifarious's solution. It will import the system version of a module, with two main differences from the previous answers:</p> <ul> <li>Supports the 'dot' notation, eg. package.module</li> <li>Is a drop-in replacement for the import statement on system modules, meaning you just have to replace that one line and if there are already calls being made to the module they will work as-is</li> </ul> <p>Put this somewhere accessible so you can call it (I have mine in my __init__.py file):</p> <pre><code>class SysModule(object): pass def import_non_local(name, local_module=None, path=None, full_name=None, accessor=SysModule()): import imp, sys, os path = path or sys.path[1:] if isinstance(path, basestring): path = [path] if '.' in name: package_name = name.split('.')[0] f, pathname, desc = imp.find_module(package_name, path) if pathname not in __path__: __path__.insert(0, pathname) imp.load_module(package_name, f, pathname, desc) v = import_non_local('.'.join(name.split('.')[1:]), None, pathname, name, SysModule()) setattr(accessor, package_name, v) if local_module: for key in accessor.__dict__.keys(): setattr(local_module, key, getattr(accessor, key)) return accessor try: f, pathname, desc = imp.find_module(name, path) if pathname not in __path__: __path__.insert(0, pathname) module = imp.load_module(name, f, pathname, desc) setattr(accessor, name, module) if local_module: for key in accessor.__dict__.keys(): setattr(local_module, key, getattr(accessor, key)) return module return accessor finally: try: if f: f.close() except: pass </code></pre> <h2>Example</h2> <p>I wanted to import mysql.connection, but I had a local package already called mysql (the official mysql utilities). So to get the connector from the system mysql package, I replaced this:</p> <pre><code>import mysql.connector </code></pre> <p>With this:</p> <pre><code>import sys from mysql.utilities import import_non_local # where I put the above function (mysql/utilities/__init__.py) import_non_local('mysql.connector', sys.modules[__name__]) </code></pre> <h2>Result</h2> <pre><code># This unmodified line further down in the file now works just fine because mysql.connector has actually become part of the namespace self.db_conn = mysql.connector.connect(**parameters) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload