django-swingcms / swingcms / modules / utilities.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys



EXCLUDE_ATTRIBUTE = ('__builtins__', '__doc__', '__file__', '__name__', '__package__')

def easy_import(module_path, obj_names, exclude=EXCLUDE_ATTRIBUTE):
    """
    Dinamically import modules. Return namespace dictionary.
    """
    mod = __import__(module_path, None, None, obj_names, -1)
    if obj_names == '*':
        if hasattr(mod, '__all__'):
            obj_names = mod.__all__
        else:
            obj_names = dir(mod)
    else:
        if not isinstance(obj_names, (tuple, list)):
            obj_names = (obj_names,)
    d = {}
    for n in obj_names:
        if n in exclude:
            continue
        d[n] = getattr(mod, n)
    d['__all__'] = obj_names
    return d


def inspect(obj, attributes=True, methods=True):
    """
    Pretty print obj.
    """
    if attributes:
        print '\nATTRIBUTES OF OBJ\n'
        for name in dir(obj):
            try:
                attr = getattr(obj, name)
                if not hasattr(attr, '__call__'):
                    print 'ATTRIBUTE %s: TYPE: %s VALUE: %s' % (name, type(attr), attr)
            except Exception, e:
                print 'on %s error: %s' % (name, str(e))
    if methods:
        print '\nMETHOD OF OBJ\n'
        for name in dir(obj):
            try:
                attr = getattr(obj, name)
                if hasattr(attr, '__call__'):
                    print 'METHOD %s: %s' % (name, attr)
            except Exception, e:
                print 'on %s error: %s' % (name, str(e))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.