'return path as an imported python module.
If modname is None, look for the containing package
and construct an according module name.
The module will be put/looked up in sys.modules.
if ensuresyspath is True then the root dir for importing
the file (taking __init__.py files into account) will
be prepended to sys.path if it isn\'t there already.
If ensuresyspath=="append" the root dir will be appended
if it isn\'t already contained in sys.path.
if ensuresyspath is False no modification of syspath happens.'

def pyimport(self, modname=None, ensuresyspath=True):

    if (not self.check()):
        raise py.error.ENOENT(self)
    pkgpath = None
    if (modname is None):
        pkgpath = self.pypkgpath()
        if (pkgpath is not None):
            pkgroot = pkgpath.dirpath()
            names = self.new(ext='').relto(pkgroot).split(self.sep)
            if (names[(-1)] == '__init__'):
                names.pop()
            modname = '.'.join(names)
        else:
            pkgroot = self.dirpath()
            modname = self.purebasename
        self._ensuresyspath(ensuresyspath, pkgroot)
        __import__(modname)
        mod = sys.modules[modname]
        if (self.basename == '__init__.py'):
            return mod
        modfile = mod.__file__
        if (modfile[(-4):] in ('.pyc', '.pyo')):
            modfile = modfile[:(-1)]
        elif modfile.endswith('$py.class'):
            modfile = (modfile[:(-9)] + '.py')
        if modfile.endswith((os.path.sep + '__init__.py')):
            if (self.basename != '__init__.py'):
                modfile = modfile[:(-12)]
        try:
            issame = self.samefile(modfile)
        except py.error.ENOENT:
            issame = False
        if (not issame):
            raise self.ImportMismatchError(modname, modfile, self)
        return mod
    else:
        try:
            return sys.modules[modname]
        except KeyError:
            mod = py.std.types.ModuleType(modname)
            mod.__file__ = str(self)
            sys.modules[modname] = mod
            try:
                py.builtin.execfile(str(self), mod.__dict__)
            except:
                del sys.modules[modname]
                raise
            return mod
