Python inspect.getmodule() Examples

The following are code examples for showing how to use inspect.getmodule(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: core-framework   Author: RedhawkSDR   File: rhunittest.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, name, bases, classdict):
        type.__init__(self, name, bases, classdict)
        spd_file = classdict.get('SPD_FILE', None)
        if spd_file:
            # Get the module that contains the test case class. This allows us
            # to find the SPD file relative to its location.
            module = inspect.getmodule(self)
            module_path = os.path.dirname(module.__file__)
            spd_path = os.path.normpath(os.path.join(module_path, spd_file))

            # Parse the SPD to get the implementation IDs.
            spd = SPDParser.parse(spd_path)
            self.__impls__ = [impl.get_id() for impl in spd.get_implementation()]

            # Update the path to the SPD file.
            self.spd_file = spd_path
        else:
            self.spd_file = None
            self.__impls__ = () 
Example 2
Project: kinect-2-libras   Author: inessadl   File: pydoc.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
    """Render text documentation, given an object or a path to an object."""
    object, name = resolve(thing, forceload)
    desc = describe(object)
    module = inspect.getmodule(object)
    if name and '.' in name:
        desc += ' in ' + name[:name.rfind('.')]
    elif module and module is not object:
        desc += ' in module ' + module.__name__
    if type(object) is _OLD_INSTANCE_TYPE:
        # If the passed object is an instance of an old-style class,
        # document its available methods instead of its value.
        object = object.__class__
    elif not (inspect.ismodule(object) or
              inspect.isclass(object) or
              inspect.isroutine(object) or
              inspect.isgetsetdescriptor(object) or
              inspect.ismemberdescriptor(object) or
              isinstance(object, property)):
        # If the passed object is a piece of data or an instance,
        # document its available methods instead of its value.
        object = type(object)
        desc += ' object'
    return title % desc + '\n\n' + text.document(object, name) 
Example 3
Project: kinect-2-libras   Author: inessadl   File: doctest.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 4
Project: Flask_Blog   Author: sugarguo   File: doctest.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is func_globals(object)
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 5
Project: abusehelper   Author: Exploit-install   File: utils.py    (license) View Source Project 6 votes vote down vote up
def format_type(value):
    """
    Return a full name of the value's type.

    >>> import abusehelper.core.events
    >>> format_type(abusehelper.core.events.Event())
    'abusehelper.core.events.Event'

    The package path prefix for builtin types gets omitted.

    >>> format_type(abusehelper.core.events)
    'module'
    >>> format_type(abusehelper.core.events.Event)
    'type'
    >>> format_type(1)
    'int'
    """

    type_ = type(value)
    name = type_.__name__
    module = inspect.getmodule(type_)
    if module is not None and module.__name__ != "__builtin__":
        name = module.__name__ + "." + name
    return name 
Example 6
Project: hostapd-mana   Author: adde88   File: dtcompat.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            # Some jython classes don't set __module__
            return module.__name__ == getattr(object, '__module__', None)
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 7
Project: hostapd-mana   Author: adde88   File: xunit.py    (license) View Source Project 6 votes vote down vote up
def nice_classname(obj):
    """Returns a nice name for class object or class instance.

        >>> nice_classname(Exception()) # doctest: +ELLIPSIS
        '...Exception'
        >>> nice_classname(Exception) # doctest: +ELLIPSIS
        '...Exception'

    """
    if inspect.isclass(obj):
        cls_name = obj.__name__
    else:
        cls_name = obj.__class__.__name__
    mod = inspect.getmodule(obj)
    if mod:
        name = mod.__name__
        # jython
        if name.startswith('org.python.core.'):
            name = name[len('org.python.core.'):]
        return "%s.%s" % (name, cls_name)
    else:
        return cls_name 
Example 8
Project: hostapd-mana   Author: adde88   File: pydoc.py    (license) View Source Project 6 votes vote down vote up
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
    """Render text documentation, given an object or a path to an object."""
    object, name = resolve(thing, forceload)
    desc = describe(object)
    module = inspect.getmodule(object)
    if name and '.' in name:
        desc += ' in ' + name[:name.rfind('.')]
    elif module and module is not object:
        desc += ' in module ' + module.__name__
    if type(object) is _OLD_INSTANCE_TYPE:
        # If the passed object is an instance of an old-style class,
        # document its available methods instead of its value.
        object = object.__class__
    elif not (inspect.ismodule(object) or
              inspect.isclass(object) or
              inspect.isroutine(object) or
              inspect.isgetsetdescriptor(object) or
              inspect.ismemberdescriptor(object) or
              isinstance(object, property)):
        # If the passed object is a piece of data or an instance,
        # document its available methods instead of its value.
        object = type(object)
        desc += ' object'
    return title % desc + '\n\n' + text.document(object, name) 
Example 9
Project: vspheretools   Author: devopshq   File: wsdl2dispatch.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, base=ServiceSOAPBinding, prefix='soap',
                 service_class=SOAPService):
        '''
        parameters:
            base -- either a class definition, or a str representing a qualified
                class name (eg. module.name.classname)
            prefix -- method prefix.
        '''
        if inspect.isclass(base):
            self.base_class_name = base.__name__
            self.base_module_name = inspect.getmodule(base).__name__
        else:
            self.base_module_name, self.base_class_name  = base.rsplit('.', 1)

        self.wsdl = None
        self.method_prefix = prefix
        self._service_class = SOAPService

        self.header  = None
        self.imports  = None
        self.messages = []
        self._services = None
        self.types_module_path = None
        self.types_module_name = None
        self.messages_module_name = None 
Example 10
Project: vspheretools   Author: devopshq   File: wsdl2dispatch.py    (license) View Source Project 6 votes vote down vote up
def setUpInitDef(self, service):
        '''set __init__ function
        '''
        assert isinstance(service, WSDLTools.Service), \
            'expecting WSDLTools.Service instance.'

        sd = self._services[service.name]
        d = sd.initdef

        if sd.location is not None:
            _,_,path,_,_,_ = urlparse.urlparse(sd.location)
            print >>d, '%sdef __init__(self, post=\'%s\', **kw):' %(self.getIndent(level=1), path)
        else:
            print >>d, '%sdef __init__(self, post, **kw):' %self.getIndent(level=1)

        # Require POST initialization value for test implementation
        if self.base_module_name == inspect.getmodule(ServiceSOAPBinding).__name__:
            print >>d, '%s%s.__init__(self, post)' %(self.getIndent(level=2), self.base_class_name)
            return

        # No POST initialization value, obtained from HTTP Request in twisted or wsgi
        print >>d, '%s%s.__init__(self)' %(self.getIndent(level=2), self.base_class_name) 
Example 11
Project: llk   Author: Tycx2ry   File: sflib.py    (license) View Source Project 6 votes vote down vote up
def debug(self, message):
        if not self.opts['_debug']:
            return
        frm = inspect.stack()[1]
        mod = inspect.getmodule(frm[0])

        if mod is None:
            modName = "Unknown"
        else:
            modName = mod.__name__

        if self.dbh is None:
            print '[' + modName + '] ' + message
        else:
            self._dblog("DEBUG", message, modName)
        return 
Example 12
Project: plotnine   Author: has2k1   File: utils.py    (license) View Source Project 6 votes vote down vote up
def alias(name, class_object):
    """
    Create an alias of a class object

    The objective of this method is to have
    an alias that is Registered. i.e If we have

        class_b = class_a

    Makes `class_b` an alias of `class_a`, but if
    `class_a` is registered by its metaclass,
    `class_b` is not. The solution

        alias('class_b', class_a)

    is equivalent to:

        class_b = class_a
        Register['class_b'] = class_a
    """
    module = inspect.getmodule(class_object)
    module.__dict__[name] = class_object
    if isinstance(class_object, Registry):
        Registry[name] = class_object 
Example 13
Project: cleverhans   Author: tensorflow   File: docscrape.py    (license) View Source Project 6 votes vote down vote up
def handle_method(method, method_name, class_name):
    method_errors = []

    # Skip out-of-library inherited methods
    module = inspect.getmodule(method)
    if module is not None:
        if not module.__name__.startswith('pylearn2'):
            return method_errors

    docstring = inspect.getdoc(method)
    if docstring is None:
        method_errors.append((class_name, method_name,
                              '**missing** method-level docstring'))
    else:
        method_errors = [
            (class_name, method_name, e) for e in
            NumpyFunctionDocString(docstring, method).get_errors()
        ]
    return method_errors 
Example 14
Project: cleverhans   Author: tensorflow   File: docscrape.py    (license) View Source Project 6 votes vote down vote up
def handle_class(val, class_name):
    cls_errors = []
    docstring = inspect.getdoc(val)
    if docstring is None:
        cls_errors.append((class_name,
                           '**missing** class-level docstring'))
    else:
        cls_errors = [
            (e,) for e in
            NumpyClassDocString(docstring, class_name, val).get_errors()
        ]
        # Get public methods and parse their docstrings
        methods = dict(((name, func) for name, func in inspect.getmembers(val)
                        if not name.startswith('_') and callable(func) and
                        type(func) is not type))
        for m_name, method in six.iteritems(methods):
            # skip error check if the method was inherited
            # from a parent class (which means it wasn't
            # defined in this source file)
            if inspect.getmodule(method) is not None:
                continue
            cls_errors.extend(handle_method(method, m_name, class_name))
    return cls_errors 
Example 15
Project: simLAB   Author: kamwar   File: html_test_runner.py    (license) View Source Project 6 votes vote down vote up
def nice_classname(obj):
    """Returns a nice name for class object or class instance.

        >>> nice_classname(Exception()) # doctest: +ELLIPSIS
        '...Exception'
        >>> nice_classname(Exception) # doctest: +ELLIPSIS
        '...Exception'

    """
    if inspect.isclass(obj):
        cls_name = obj.__name__
    else:
        cls_name = obj.__class__.__name__
    mod = inspect.getmodule(obj)
    if mod:
        name = mod.__name__
        # jython
        if name.startswith('org.python.core.'):
            name = name[len('org.python.core.'):]
        return "%s.%s" % (name, cls_name)
    else:
        return cls_name 
Example 16
Project: spiderfoot   Author: wi-fi-analyzer   File: sflib.py    (license) View Source Project 6 votes vote down vote up
def info(self, message):
        frm = inspect.stack()[1]
        mod = inspect.getmodule(frm[0])

        if mod is None:
            modName = "Unknown"
        else:
            if mod.__name__ == "sflib":
                frm = inspect.stack()[2]
                mod = inspect.getmodule(frm[0])
                if mod is None:
                    modName = "Unknown"
                else:
                    modName = mod.__name__
            else:
                modName = mod.__name__

        if self.dbh is None:
            print '[' + modName + '] ' + message
        else:
            self._dblog("INFO", message, modName)
        return 
Example 17
Project: spiderfoot   Author: wi-fi-analyzer   File: sflib.py    (license) View Source Project 6 votes vote down vote up
def debug(self, message):
        if not self.opts['_debug']:
            return
        frm = inspect.stack()[1]
        mod = inspect.getmodule(frm[0])

        if mod is None:
            modName = "Unknown"
        else:
            if mod.__name__ == "sflib":
                frm = inspect.stack()[2]
                mod = inspect.getmodule(frm[0])
                if mod is None:
                    modName = "Unknown"
                else:
                    modName = mod.__name__
            else:
                modName = mod.__name__

        if self.dbh is None:
            print '[' + modName + '] ' + message
        else:
            self._dblog("DEBUG", message, modName)
        return 
Example 18
Project: aws-cfn-plex   Author: lordmuffin   File: yacc.py    (license) View Source Project 6 votes vote down vote up
def validate_error_func(self):
        if self.error_func:
            if isinstance(self.error_func, types.FunctionType):
                ismethod = 0
            elif isinstance(self.error_func, types.MethodType):
                ismethod = 1
            else:
                self.log.error("'p_error' defined, but is not a function or method")
                self.error = True
                return

            eline = self.error_func.__code__.co_firstlineno
            efile = self.error_func.__code__.co_filename
            module = inspect.getmodule(self.error_func)
            self.modules.add(module)

            argcount = self.error_func.__code__.co_argcount - ismethod
            if argcount != 1:
                self.log.error('%s:%d: p_error() requires 1 argument', efile, eline)
                self.error = True

    # Get the tokens map 
Example 19
Project: aws-cfn-plex   Author: lordmuffin   File: yacc.py    (license) View Source Project 6 votes vote down vote up
def get_pfunctions(self):
        p_functions = []
        for name, item in self.pdict.items():
            if not name.startswith('p_') or name == 'p_error':
                continue
            if isinstance(item, (types.FunctionType, types.MethodType)):
                line = item.__code__.co_firstlineno
                module = inspect.getmodule(item)
                p_functions.append((line, module, name, item.__doc__))

        # Sort all of the actions by line number; make sure to stringify
        # modules to make them sortable, since `line` may not uniquely sort all
        # p functions
        p_functions.sort(key=lambda p_function: (
            p_function[0],
            str(p_function[1]),
            p_function[2],
            p_function[3]))
        self.pfuncs = p_functions

    # Validate all of the p_functions 
Example 20
Project: Intranet-Penetration   Author: yuxiaokui   File: doctest.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 21
Project: Intranet-Penetration   Author: yuxiaokui   File: apiproxy_stub_map.py    (license) View Source Project 6 votes vote down vote up
def __Insert(self, index, key, function, service=None):
    """Appends a hook at a certain position in the list.

    Args:
      index: the index of where to insert the function
      key: a unique key (within the module) for this particular function.
        If something from the same module with the same key is already
        registered, nothing will be added.
      function: the hook to be added.
      service: optional argument that restricts the hook to a particular api

    Returns:
      True if the collection was modified.
    """
    unique_key = (key, inspect.getmodule(function))
    if unique_key in self.__unique_keys:
      return False
    num_args = len(inspect.getargspec(function)[0])
    if (inspect.ismethod(function)):
      num_args -= 1
    self.__content.insert(index, (key, function, service, num_args))
    self.__unique_keys.add(unique_key)
    return True 
Example 22
Project: flasky   Author: RoseOu   File: doctest.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is func_globals(object)
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 23
Project: MKFQ   Author: maojingios   File: doctest.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 24
Project: MKFQ   Author: maojingios   File: apiproxy_stub_map.py    (license) View Source Project 6 votes vote down vote up
def __Insert(self, index, key, function, service=None):
    """Appends a hook at a certain position in the list.

    Args:
      index: the index of where to insert the function
      key: a unique key (within the module) for this particular function.
        If something from the same module with the same key is already
        registered, nothing will be added.
      function: the hook to be added.
      service: optional argument that restricts the hook to a particular api

    Returns:
      True if the collection was modified.
    """
    unique_key = (key, inspect.getmodule(function))
    if unique_key in self.__unique_keys:
      return False
    num_args = len(inspect.getargspec(function)[0])
    if (inspect.ismethod(function)):
      num_args -= 1
    self.__content.insert(index, (key, function, service, num_args))
    self.__unique_keys.add(unique_key)
    return True 
Example 25
Project: sahriswiki   Author: prologic   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def loadMacros():
    path = os.path.abspath(os.path.dirname(__file__))
    p = lambda x: os.path.splitext(x)[1] == ".py"
    modules = [x for x in os.listdir(path) if p(x) and not x == "__init__.py"]

    macros = {}

    for module in modules:
        name, _ = os.path.splitext(module)

        moduleName = "%s.%s" % (__package__, name)
        m = __import__(moduleName, globals(), locals(), __package__)

        p = lambda x: isfunction(x) and getmodule(x) is m
        for name, function in getmembers(m, p):
            name = name.replace("_", "-")
            try:
                macros[name] = function
            except Exception, e:
                continue

    return macros 
Example 26
Project: pydecor   Author: mplanchard   File: functions.py    (license) View Source Project 6 votes vote down vote up
def log_call(decorated, logger=None, level='info',
             format_str=LOG_CALL_FMT_STR):
    """Log the parameters & results of a function call

    Designed to be called via the ``after`` decorator with
    ``pass_params=True`` and ``pass_decorated=True``. Use
    :any:`decorators.log_call` for easiest invocation.

    :param Decorated decorated: decorated function information
    :param Optional[logging.Logger] logger: optional logger instance
    :param Optional[str] level: log level - must be an acceptable Python
        log level, case-insensitive
    :param format_str: the string to use when formatting the results
    """
    if logger is None:
        name = getmodule(decorated.wrapped).__name__
        logger = getLogger(name)
    log_fn = getattr(logger, level.lower())
    msg = format_str.format(
        name=decorated.wrapped.__name__,
        args=decorated.args,
        kwargs=decorated.kwargs,
        result=decorated.result
    )
    log_fn(msg) 
Example 27
Project: django-schemas   Author: ryannjohnson   File: utils.py    (license) View Source Project 6 votes vote down vote up
def get_class_that_defined_method(meth):
    """Returns the class that created the given method.
    
    A helper function for finding class methods amongst a list of many
    methods. 
    
    Source:
        http://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3/25959545#25959545
    """
    if inspect.ismethod(meth):
        for cls in inspect.getmro(meth.__self__.__class__):
           if cls.__dict__.get(meth.__name__) is meth:
                return cls
        meth = meth.__func__ # fallback to __qualname__ parsing
    if inspect.isfunction(meth):
        
        # Check to make sure the method has a "qualname"
        if not getattr(meth, '__qualname__', None):
            return None
        
        cls = getattr(inspect.getmodule(meth),
                      meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0])
        if isinstance(cls, type):
            return cls
    return None # not required since None would have been implicitly returned anyway 
Example 28
Project: leetcode   Author: thomasyimgit   File: ipdoctest.py    (license) View Source Project 6 votes vote down vote up
def makeTest(self, obj, parent):
        """Look for doctests in the given object, which will be a
        function, method or class.
        """
        #print 'Plugin analyzing:', obj, parent  # dbg
        # always use whitespace and ellipsis options
        optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS

        doctests = self.finder.find(obj, module=getmodule(parent))
        if doctests:
            for test in doctests:
                if len(test.examples) == 0:
                    continue

                yield DocTestCase(test, obj=obj,
                                  optionflags=optionflags,
                                  checker=self.checker) 
Example 29
Project: zippy   Author: securesystemslab   File: pydoc.py    (license) View Source Project 6 votes vote down vote up
def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
        renderer=None):
    """Render text documentation, given an object or a path to an object."""
    if renderer is None:
        renderer = text
    object, name = resolve(thing, forceload)
    desc = describe(object)
    module = inspect.getmodule(object)
    if name and '.' in name:
        desc += ' in ' + name[:name.rfind('.')]
    elif module and module is not object:
        desc += ' in module ' + module.__name__

    if not (inspect.ismodule(object) or
              inspect.isclass(object) or
              inspect.isroutine(object) or
              inspect.isgetsetdescriptor(object) or
              inspect.ismemberdescriptor(object) or
              isinstance(object, property)):
        # If the passed object is a piece of data or an instance,
        # document its available methods instead of its value.
        object = type(object)
        desc += ' object'
    return title % desc + '\n\n' + renderer.document(object, name) 
Example 30
Project: zippy   Author: securesystemslab   File: doctest.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif inspect.isfunction(object):
            return module.__dict__ is object.__globals__
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 31
Project: pytypes   Author: Stewori   File: util.py    (license) View Source Project 6 votes vote down vote up
def get_class_that_defined_method(meth):
    """Determines the class owning the given method.
    """
    if is_classmethod(meth):
        return meth.__self__
    if hasattr(meth, 'im_class'):
        return meth.im_class
    elif hasattr(meth, '__qualname__'):
        # Python 3
        try:
            cls_names = meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0].split('.')
            cls = inspect.getmodule(meth)
            for cls_name in cls_names:
                cls = getattr(cls, cls_name)
            if isinstance(cls, type):
                return cls
        except AttributeError:
            # If this was called from a decorator and meth is not a method, this
            # can result in AttributeError, because at decorator-time meth has not
            # yet been added to module. If it's really a method, its class would be
            # already in, so no problem in that case.
            pass
    raise ValueError(str(meth)+' is not a method.') 
Example 32
Project: pytypes   Author: Stewori   File: util.py    (license) View Source Project 6 votes vote down vote up
def getmodule(code):
    """More robust variant of inspect.getmodule.
    E.g. has less issues on Jython.
    """
    try:
        md = inspect.getmodule(code, code.co_filename)
    except AttributeError:
        return inspect.getmodule(code)
    if md is None:
        # Jython-specific:
        # This is currently just a crutch; todo: resolve __pyclasspath__ properly!
        cfname = code.co_filename.replace('__pyclasspath__',
                os.path.realpath('')+os.sep+'__pyclasspath__')
        cfname = cfname.replace('$py.class', '.py')
        md = inspect.getmodule(code, cfname)
    if md is None:
        md = inspect.getmodule(code)
    return md 
Example 33
Project: pytypes   Author: Stewori   File: util.py    (license) View Source Project 6 votes vote down vote up
def get_callable_fq_for_code(code, locals_dict = None):
    """Determines the function belonging to a given code object in a fully qualified fashion.
    Returns a tuple consisting of
    - the callable
    - a list of classes and inner classes, locating the callable (like a fully qualified name)
    - the corresponding self object, if the callable is a method
    """
    if code in _code_callable_dict:
        res = _code_callable_dict[code]
        if not res[0] is None or locals_dict is None:
            return res
    md = getmodule(code)
    if not md is None:
        nesting = []
        res, slf = _get_callable_fq_for_code(code, md, md, False, nesting, set())
        if res is None and not locals_dict is None:
            nesting = []
            res, slf = _get_callable_from_locals(code, locals_dict, md, False, nesting)
        else:
            _code_callable_dict[code] = (res, nesting, slf)
        return res, nesting, slf
    else:
        return None, None, None 
Example 34
Project: chihu   Author: yelongyu   File: doctest.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is func_globals(object)
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 35
Project: Price-Comparator   Author: Thejas-1   File: doctest.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is func_globals(object)
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 36
Project: oil   Author: oilshell   File: pydoc.py    (license) View Source Project 6 votes vote down vote up
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
    """Render text documentation, given an object or a path to an object."""
    object, name = resolve(thing, forceload)
    desc = describe(object)
    module = inspect.getmodule(object)
    if name and '.' in name:
        desc += ' in ' + name[:name.rfind('.')]
    elif module and module is not object:
        desc += ' in module ' + module.__name__
    if type(object) is _OLD_INSTANCE_TYPE:
        # If the passed object is an instance of an old-style class,
        # document its available methods instead of its value.
        object = object.__class__
    elif not (inspect.ismodule(object) or
              inspect.isclass(object) or
              inspect.isroutine(object) or
              inspect.isgetsetdescriptor(object) or
              inspect.ismemberdescriptor(object) or
              isinstance(object, property)):
        # If the passed object is a piece of data or an instance,
        # document its available methods instead of its value.
        object = type(object)
        desc += ' object'
    return title % desc + '\n\n' + text.document(object, name) 
Example 37
Project: oil   Author: oilshell   File: doctest.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 38
Project: python2-tracer   Author: extremecoders-re   File: pydoc.py    (license) View Source Project 6 votes vote down vote up
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
    """Render text documentation, given an object or a path to an object."""
    object, name = resolve(thing, forceload)
    desc = describe(object)
    module = inspect.getmodule(object)
    if name and '.' in name:
        desc += ' in ' + name[:name.rfind('.')]
    elif module and module is not object:
        desc += ' in module ' + module.__name__
    if type(object) is _OLD_INSTANCE_TYPE:
        # If the passed object is an instance of an old-style class,
        # document its available methods instead of its value.
        object = object.__class__
    elif not (inspect.ismodule(object) or
              inspect.isclass(object) or
              inspect.isroutine(object) or
              inspect.isgetsetdescriptor(object) or
              inspect.ismemberdescriptor(object) or
              isinstance(object, property)):
        # If the passed object is a piece of data or an instance,
        # document its available methods instead of its value.
        object = type(object)
        desc += ' object'
    return title % desc + '\n\n' + text.document(object, name) 
Example 39
Project: python2-tracer   Author: extremecoders-re   File: doctest.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 40
Project: highway.py   Author: PhilipTrauner   File: log.py    (license) View Source Project 6 votes vote down vote up
def print_out(message, color, file):
	stack_ = stack()
	# Interestingly the if statement below is not executed when excepting KeyboardInterrupts. Weird.
	# To prevent a crash we assume the module's name is 'Unknown'
	module = "Unknown"
	if getmodule(stack_[2][0]) == None:
		for i in stack_[2:]:
			if getmodule(i[0]) != None:
				try:
					module = CACHED_MODULES[i[0].f_code]
				except KeyError:
					module = getmodule(i[0]).__name__
					CACHED_MODULES[i[0].f_code] = module
	else:
		try:
			module = CACHED_MODULES[stack_[2][0].f_code]
		except KeyError:
			module = getmodule(stack_[2][0]).__name__
			CACHED_MODULES[stack_[2][0].f_code] = module
	print("\033[32m%s\033[0m:%i ? %s%s\033[0m" % (
		module, stack_[2][0].f_lineno, color, 
		message), file=file)
	file.flush() 
Example 41
Project: sslstrip-hsts-openwrt   Author: adde88   File: dtcompat.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            # Some jython classes don't set __module__
            return module.__name__ == getattr(object, '__module__', None)
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 42
Project: sslstrip-hsts-openwrt   Author: adde88   File: xunit.py    (license) View Source Project 6 votes vote down vote up
def nice_classname(obj):
    """Returns a nice name for class object or class instance.

        >>> nice_classname(Exception()) # doctest: +ELLIPSIS
        '...Exception'
        >>> nice_classname(Exception) # doctest: +ELLIPSIS
        '...Exception'

    """
    if inspect.isclass(obj):
        cls_name = obj.__name__
    else:
        cls_name = obj.__class__.__name__
    mod = inspect.getmodule(obj)
    if mod:
        name = mod.__name__
        # jython
        if name.startswith('org.python.core.'):
            name = name[len('org.python.core.'):]
        return "%s.%s" % (name, cls_name)
    else:
        return cls_name 
Example 43
Project: sslstrip-hsts-openwrt   Author: adde88   File: pydoc.py    (license) View Source Project 6 votes vote down vote up
def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
    """Render text documentation, given an object or a path to an object."""
    object, name = resolve(thing, forceload)
    desc = describe(object)
    module = inspect.getmodule(object)
    if name and '.' in name:
        desc += ' in ' + name[:name.rfind('.')]
    elif module and module is not object:
        desc += ' in module ' + module.__name__
    if type(object) is _OLD_INSTANCE_TYPE:
        # If the passed object is an instance of an old-style class,
        # document its available methods instead of its value.
        object = object.__class__
    elif not (inspect.ismodule(object) or
              inspect.isclass(object) or
              inspect.isroutine(object) or
              inspect.isgetsetdescriptor(object) or
              inspect.ismemberdescriptor(object) or
              isinstance(object, property)):
        # If the passed object is a piece of data or an instance,
        # document its available methods instead of its value.
        object = type(object)
        desc += ' object'
    return title % desc + '\n\n' + text.document(object, name) 
Example 44
Project: Flask-NvRay-Blog   Author: rui7157   File: doctest.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is func_globals(object)
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 45
Project: NeuroMobile   Author: AndrewADykman   File: doctest.py    (license) View Source Project 6 votes vote down vote up
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is func_globals(object)
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function") 
Example 46
Project: packetweaver   Author: ANSSI-FR   File: ability_module.py    (license) View Source Project 6 votes vote down vote up
def get_ability_instance_by_name(self, name, module_factory):
        # First, we reload the ability, just in case it changed on disk
        for abl in self._mod.exported_abilities:
            if abl.get_name() == name:
                reload(inspect.getmodule(abl))
        # We need to reload the "module" because the submodule were reloaded too
        self._mod = module_factory.reload_module(self._mod_path)

        for abl in self._mod.exported_abilities:
            if abl.get_name() == name:
                opts = {k: v for k, v in self._defaults.items() if k in abl.get_option_list()}
                return abl(
                    module_factory,
                    default_opts=opts,
                    view=self._view
                )
        return None 
Example 47
Project: esper   Author: scanner-research   File: queries.py    (license) View Source Project 6 votes vote down vote up
def query(name):
    frame = inspect.stack()[1]
    module = inspect.getmodule(frame[0])
    filename = module.__file__
    dataset = os.path.abspath(filename).split('/')[-2]

    def wrapper(f):
        lines = inspect.getsource(f).split('\n')
        lines = lines[:-1]  # Seems to include a trailing newline

        # Hacky way to get just the function body
        i = 0
        while True:
            if "():" in lines[i]:
                break
            i = i + 1

        fn = lines[i:]
        fn += ['FN = ' + f.__name__]
        queries[dataset].append([name, '\n'.join(fn)])

        return f

    return wrapper 
Example 48
Project: logfury   Author: ppolewicz   File: utils.py    (license) View Source Project 6 votes vote down vote up
def get_class_that_defined_method(meth):
    if inspect.ismethod(meth):
        for cls in inspect.getmro(meth.__self__.__class__):
            if cls.__dict__.get(meth.__name__) is meth:
                return cls
        meth = meth.__func__  # fallback to __qualname__ parsing
    if inspect.isfunction(meth):
        if not hasattr(meth, '__qualname__'):
            pass  # python too old
        else:
            try:
                cls = getattr(
                    inspect.getmodule(meth),
                    meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0]
                )  # yapf: disable
            except AttributeError:  # defined in an exec() on new python?
                cls = 'exec'
            if isinstance(cls, type):
                return cls
    return None 
Example 49
Project: web_ctp   Author: molebot   File: pydoc.py    (license) View Source Project 6 votes vote down vote up
def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
        renderer=None):
    """Render text documentation, given an object or a path to an object."""
    if renderer is None:
        renderer = text
    object, name = resolve(thing, forceload)
    desc = describe(object)
    module = inspect.getmodule(object)
    if name and '.' in name:
        desc += ' in ' + name[:name.rfind('.')]
    elif module and module is not object:
        desc += ' in module ' + module.__name__

    if not (inspect.ismodule(object) or
              inspect.isclass(object) or
              inspect.isroutine(object) or
              inspect.isgetsetdescriptor(object) or
              inspect.ismemberdescriptor(object) or
              isinstance(object, property)):
        # If the passed object is a piece of data or an instance,
        # document its available methods instead of its value.
        object = type(object)
        desc += ' object'
    return title % desc + '\n\n' + renderer.document(object, name) 
Example 50
Project: splunk_ta_ps4_f1_2016   Author: jonathanvarley   File: yacc.py    (license) View Source Project 6 votes vote down vote up
def validate_error_func(self):
        if self.error_func:
            if isinstance(self.error_func, types.FunctionType):
                ismethod = 0
            elif isinstance(self.error_func, types.MethodType):
                ismethod = 1
            else:
                self.log.error("'p_error' defined, but is not a function or method")
                self.error = True
                return

            eline = self.error_func.__code__.co_firstlineno
            efile = self.error_func.__code__.co_filename
            module = inspect.getmodule(self.error_func)
            self.modules.add(module)

            argcount = self.error_func.__code__.co_argcount - ismethod
            if argcount != 1:
                self.log.error('%s:%d: p_error() requires 1 argument', efile, eline)
                self.error = True

    # Get the tokens map