easy_import.py :  » Content-Management-Systems » PyLucid » PyLucid_standalone » dbpreferences » tools » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Content Management Systems » PyLucid 
PyLucid » PyLucid_standalone » dbpreferences » tools » easy_import.py
# -*- coding: utf-8 -*-

"""
    Import2
    ~~~~~~~

    a easy to use __import__

    Last commit info:
    ~~~~~~~~~~~~~~~~~
    $LastChangedDate: 2009-04-18 10:58:43 +0100 (Sa, 18 Apr 2009) $
    $Rev: 1903 $
    $Author: JensDiemer $

    :copyleft: 2008 by the PyLucid team, see AUTHORS for more details.
    :license: GNU GPL v3 or above, see LICENSE for more details.
"""

#______________________________________________________________________________
# internal import functions

def import2(from_name, fromlist=None, globals={}, locals={}):
    """
    A easy __import__ function.
    TODO: Python 2.5 level argument not supported, yet.
    Link: http://www.python-forum.de/topic-14591.html (de)

    >>> import sys
    >>> sys2 = import2("sys")
    >>> sys is sys2
    True

    >>> from time import time
    >>> time2 = import2("time", "time")
    >>> time is time2
    True

    >>> from os.path import sep
    >>> sep2 = import2("os.path", "sep")
    >>> sep is sep2
    True

    >>> from os import sep, pathsep
    >>> sep2, pathsep2 = import2("os", ["sep", "pathsep"])
    >>> sep is sep2 ; pathsep is pathsep2
    True
    True

    >>> import2("existiertnicht")
    Traceback (most recent call last):
        ...
    ImportError: No module named existiertnicht

    >>> import2("os", "gibtsnicht")
    Traceback (most recent call last):
        ...
    AttributeError: 'os' object has no attribute 'gibtsnicht
    """

    if isinstance(fromlist, basestring):
        # Only one from objects name
        fromlist = [fromlist]

    obj = __import__(from_name, globals, locals, fromlist)
    if fromlist==None:
        # Without a fromlist
        return obj

    # get all 'fromlist' objects
    result = []
    for object_name in fromlist:
        try:
            result.append(getattr(obj, object_name))
        except AttributeError, e:
            msg = "'%s' object has no attribute '%s" % (
                obj.__name__, object_name
            )
            raise AttributeError(msg)

    if len(result) == 1:
        return result[0]
    else:
        return result


def import3(from_name, object_name):
    """
    Thin layer aroung import2():
      - other error handling: raise original error or always a ImportError
      - catch SyntaxError, too (e.g. developing a PyLucid plugin)
      - convert unicode to string (Names from database are always unicode and
        the __import__ function must get strings)

    >>> from time import time
    >>> time2 = import3(u"time", u"time")
    >>> time is time2
    True

    >>> import3(u"A", u"B")
    Traceback (most recent call last):
        ...
    ImportError: Can't import 'B' from 'A': No module named A
    """
    try:
        # unicode -> string
        from_name = str(from_name)
        object_name = str(object_name)

        return import2(from_name, object_name)
    except (ImportError, SyntaxError), err:
        raise ImportError, "Can't import '%s' from '%s': %s" % (
            object_name, from_name, err
        )



if __name__ == "__main__":
    print "runnint doctest for %s" % __file__
    verbose = False
#    verbose = True
    import doctest
    doctest.testmod(verbose=verbose)
    print "--- END ---"
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.