Python twisted.python.reflect.namedAny() Examples

The following are 30 code examples of twisted.python.reflect.namedAny(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.python.reflect , or try the search function .
Example #1
Source File: runner.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def filenameToModule(fn):
    if not os.path.exists(fn):
        raise ValueError("%r doesn't exist" % (fn,))
    try:
        ret = reflect.namedAny(reflect.filenameToModuleName(fn))
    except (ValueError, AttributeError):
        # Couldn't find module.  The file 'fn' is not in PYTHONPATH
        return _importFromFile(fn)
    # ensure that the loaded module matches the file
    retFile = os.path.splitext(ret.__file__)[0] + '.py'
    # not all platforms (e.g. win32) have os.path.samefile
    same = getattr(os.path, 'samefile', samefile)
    if os.path.isfile(fn) and not same(fn, retFile):
        del sys.modules[ret.__name__]
        ret = _importFromFile(fn)
    return ret 
Example #2
Source File: styles.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _unpickleFunction(fullyQualifiedName):
    """
    Convert a function name into a function by importing it.

    This is a synonym for L{twisted.python.reflect.namedAny}, but imported
    locally to avoid circular imports, and also to provide a persistent name
    that can be stored (and deprecated) independently of C{namedAny}.

    @param fullyQualifiedName: The fully qualified name of a function.
    @type fullyQualifiedName: native C{str}

    @return: A function object imported from the given location.
    @rtype: L{types.FunctionType}
    """
    from twisted.python.reflect import namedAny
    return namedAny(fullyQualifiedName) 
Example #3
Source File: reactormixins.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def makeTestCaseClasses(cls):
        """
        Create a L{SynchronousTestCase} subclass which mixes in C{cls} for each
        known reactor and return a dict mapping their names to them.
        """
        classes = {}
        for reactor in cls._reactors:
            shortReactorName = reactor.split(".")[-1]
            name = (cls.__name__ + "." + shortReactorName + "Tests").replace(".", "_")
            class testcase(cls, SynchronousTestCase):
                __module__ = cls.__module__
                if reactor in cls.skippedReactors:
                    skip = cls.skippedReactors[reactor]
                try:
                    reactorFactory = namedAny(reactor)
                except:
                    skip = Failure().getErrorMessage()
            testcase.__name__ = name
            if hasattr(cls, "__qualname__"):
                testcase.__qualname__ = ".".join(cls.__qualname__.split()[0:-1] + [name])
            classes[testcase.__name__] = testcase
        return classes 
Example #4
Source File: test_reflect.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_attributeExceptions(self):
        """
        If segments on the end of a fully-qualified Python name represents
        attributes which aren't actually present on the object represented by
        the earlier segments, L{namedAny} should raise an L{AttributeError}.
        """
        self.assertRaises(
            AttributeError,
            reflect.namedAny, "twisted.nosuchmoduleintheworld")
        # ImportError behaves somewhat differently between "import
        # extant.nonextant" and "import extant.nonextant.nonextant", so test
        # the latter as well.
        self.assertRaises(
            AttributeError,
            reflect.namedAny, "twisted.nosuch.modulein.theworld")
        self.assertRaises(
            AttributeError,
            reflect.namedAny,
            "twisted.test.test_reflect.Summer.nosuchattribute") 
Example #5
Source File: test_modules.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_loadPackagesAndModules(self):
        """
        Verify that we can locate and load packages, modules, submodules, and
        subpackages.
        """
        for n in ['os',
                  'twisted',
                  'twisted.python',
                  'twisted.python.reflect']:
            m = namedAny(n)
            self.failUnlessIdentical(
                modules.getModule(n).load(),
                m)
            self.failUnlessIdentical(
                self.findByIteration(n).load(),
                m) 
Example #6
Source File: reactormixins.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def makeTestCaseClasses(cls):
        """
        Create a L{SynchronousTestCase} subclass which mixes in C{cls} for each
        known reactor and return a dict mapping their names to them.
        """
        classes = {}
        for reactor in cls._reactors:
            shortReactorName = reactor.split(".")[-1]
            name = (cls.__name__ + "." + shortReactorName + "Tests").replace(".", "_")
            class testcase(cls, SynchronousTestCase):
                __module__ = cls.__module__
                if reactor in cls.skippedReactors:
                    skip = cls.skippedReactors[reactor]
                try:
                    reactorFactory = namedAny(reactor)
                except:
                    skip = Failure().getErrorMessage()
            testcase.__name__ = name
            if hasattr(cls, "__qualname__"):
                testcase.__qualname__ = ".".join(cls.__qualname__.split()[0:-1] + [name])
            classes[testcase.__name__] = testcase
        return classes 
Example #7
Source File: styles.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _unpickleFunction(fullyQualifiedName):
    """
    Convert a function name into a function by importing it.

    This is a synonym for L{twisted.python.reflect.namedAny}, but imported
    locally to avoid circular imports, and also to provide a persistent name
    that can be stored (and deprecated) independently of C{namedAny}.

    @param fullyQualifiedName: The fully qualified name of a function.
    @type fullyQualifiedName: native C{str}

    @return: A function object imported from the given location.
    @rtype: L{types.FunctionType}
    """
    from twisted.python.reflect import namedAny
    return namedAny(fullyQualifiedName) 
Example #8
Source File: test_reflect.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_attributeExceptions(self):
        """
        If segments on the end of a fully-qualified Python name represents
        attributes which aren't actually present on the object represented by
        the earlier segments, L{namedAny} should raise an L{AttributeError}.
        """
        self.assertRaises(
            AttributeError,
            reflect.namedAny, "twisted.nosuchmoduleintheworld")
        # ImportError behaves somewhat differently between "import
        # extant.nonextant" and "import extant.nonextant.nonextant", so test
        # the latter as well.
        self.assertRaises(
            AttributeError,
            reflect.namedAny, "twisted.nosuch.modulein.theworld")
        self.assertRaises(
            AttributeError,
            reflect.namedAny,
            "twisted.test.test_reflect.Summer.nosuchattribute") 
Example #9
Source File: test_modules.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_loadPackagesAndModules(self):
        """
        Verify that we can locate and load packages, modules, submodules, and
        subpackages.
        """
        for n in ['os',
                  'twisted',
                  'twisted.python',
                  'twisted.python.reflect']:
            m = namedAny(n)
            self.failUnlessIdentical(
                modules.getModule(n).load(),
                m)
            self.failUnlessIdentical(
                self.findByIteration(n).load(),
                m) 
Example #10
Source File: reactormixins.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def makeTestCaseClasses(cls):
        """
        Create a L{TestCase} subclass which mixes in C{cls} for each known
        reactor and return a dict mapping their names to them.
        """
        classes = {}
        for reactor in cls._reactors:
            shortReactorName = reactor.split(".")[-1]
            name = (cls.__name__ + "." + shortReactorName).replace(".", "_")
            class testcase(cls, TestCase):
                __module__ = cls.__module__
                if reactor in cls.skippedReactors:
                    skip = cls.skippedReactors[reactor]
                try:
                    reactorFactory = namedAny(reactor)
                except:
                    skip = Failure().getErrorMessage()
            testcase.__name__ = name
            classes[testcase.__name__] = testcase
        return classes 
Example #11
Source File: test_reflect.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_importExceptions(self):
        """
        Exceptions raised by modules which L{namedAny} causes to be imported
        should pass through L{namedAny} to the caller.
        """
        self.assertRaises(
            ZeroDivisionError,
            reflect.namedAny, "twisted.test.reflect_helper_ZDE")
        # Make sure that this behavior is *consistent* for 2.3, where there is
        # no post-failed-import cleanup
        self.assertRaises(
            ZeroDivisionError,
            reflect.namedAny, "twisted.test.reflect_helper_ZDE")
        self.assertRaises(
            ValueError,
            reflect.namedAny, "twisted.test.reflect_helper_VE")
        # Modules which themselves raise ImportError when imported should result in an ImportError
        self.assertRaises(
            ImportError,
            reflect.namedAny, "twisted.test.reflect_helper_IE") 
Example #12
Source File: test_reflect.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_attributeExceptions(self):
        """
        If segments on the end of a fully-qualified Python name represents
        attributes which aren't actually present on the object represented by
        the earlier segments, L{namedAny} should raise an L{AttributeError}.
        """
        self.assertRaises(
            AttributeError,
            reflect.namedAny, "twisted.nosuchmoduleintheworld")
        # ImportError behaves somewhat differently between "import
        # extant.nonextant" and "import extant.nonextant.nonextant", so test
        # the latter as well.
        self.assertRaises(
            AttributeError,
            reflect.namedAny, "twisted.nosuch.modulein.theworld")
        self.assertRaises(
            AttributeError,
            reflect.namedAny, "twisted.python.reflect.Summer.nosuchattributeintheworld") 
Example #13
Source File: test_modules.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_loadPackagesAndModules(self):
        """
        Verify that we can locate and load packages, modules, submodules, and
        subpackages.
        """
        for n in ['os',
                  'twisted',
                  'twisted.python',
                  'twisted.python.reflect']:
            m = namedAny(n)
            self.failUnlessIdentical(
                modules.getModule(n).load(),
                m)
            self.failUnlessIdentical(
                self.findByIteration(n).load(),
                m) 
Example #14
Source File: runner.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def filenameToModule(fn):
    """
    Given a filename, do whatever possible to return a module object matching
    that file.

    If the file in question is a module in Python path, properly import and
    return that module. Otherwise, load the source manually.

    @param fn: A filename.
    @return: A module object.
    @raise ValueError: If C{fn} does not exist.
    """
    if not os.path.exists(fn):
        raise ValueError("%r doesn't exist" % (fn,))
    try:
        ret = reflect.namedAny(reflect.filenameToModuleName(fn))
    except (ValueError, AttributeError):
        # Couldn't find module.  The file 'fn' is not in PYTHONPATH
        return _importFromFile(fn)

    if not hasattr(ret, "__file__"):
        # This isn't a Python module in a package, so import it from a file
        return _importFromFile(fn)

    # ensure that the loaded module matches the file
    retFile = os.path.splitext(ret.__file__)[0] + '.py'
    # not all platforms (e.g. win32) have os.path.samefile
    same = getattr(os.path, 'samefile', samefile)
    if os.path.isfile(fn) and not same(fn, retFile):
        del sys.modules[ret.__name__]
        ret = _importFromFile(fn)
    return ret 
Example #15
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_namedAnySecondAttributeLookup(self):
        """
        L{namedAny} should return the object an attribute of an object which
        itself was an attribute of a non-module, non-package object is bound to
        for the name it is passed.
        """
        self.assertIdentical(
            reflect.namedAny(
                "twisted.python.reflect.Summer.reallySet.__doc__"),
            reflect.Summer.reallySet.__doc__) 
Example #16
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_namedAnyAttributeLookup(self):
        """
        L{namedAny} should return the object an attribute of a non-module,
        non-package object is bound to for the name it is passed.
        """
        # Note - not assertEqual because unbound method lookup creates a new
        # object every time.  This is a foolishness of Python's object
        # implementation, not a bug in Twisted.
        self.assertEqual(
            reflect.namedAny("twisted.python.reflect.Summer.reallySet"),
            reflect.Summer.reallySet) 
Example #17
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_namedAnyModuleLookup(self):
        """
        L{namedAny} should return the module object for the name it is passed.
        """
        self.assertIdentical(
            reflect.namedAny("twisted.python.reflect"), reflect) 
Example #18
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_namedAnyPackageLookup(self):
        """
        L{namedAny} should return the package object for the name it is passed.
        """
        import twisted.python
        self.assertIdentical(
            reflect.namedAny("twisted.python"), twisted.python) 
Example #19
Source File: test_reflect.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testClassLookup(self):
        self.failUnlessIdentical(reflect.namedAny("twisted.python."
                                                  "reflect.Summer"),
                                 reflect.Summer) 
Example #20
Source File: plugin.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def load(self):
        return namedAny(self.dropin.moduleName + '.' + self.name) 
Example #21
Source File: runner.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def loadDoctests(self, module):
        """
        Return a suite of tests for all the doctests defined in C{module}.

        @param module: A module object or a module name.
        """
        if isinstance(module, str):
            try:
                module = reflect.namedAny(module)
            except:
                return ErrorHolder(module, failure.Failure())
        if not inspect.ismodule(module):
            warnings.warn("trial only supports doctesting modules")
            return
        extraArgs = {}
        if sys.version_info > (2, 4):
            # Work around Python issue2604: DocTestCase.tearDown clobbers globs
            def saveGlobals(test):
                """
                Save C{test.globs} and replace it with a copy so that if
                necessary, the original will be available for the next test
                run.
                """
                test._savedGlobals = getattr(test, '_savedGlobals', test.globs)
                test.globs = test._savedGlobals.copy()
            extraArgs['setUp'] = saveGlobals
        return doctest.DocTestSuite(module, **extraArgs) 
Example #22
Source File: runner.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def filenameToModule(fn):
    """
    Given a filename, do whatever possible to return a module object matching
    that file.

    If the file in question is a module in Python path, properly import and
    return that module. Otherwise, load the source manually.

    @param fn: A filename.
    @return: A module object.
    @raise ValueError: If C{fn} does not exist.
    """
    if not os.path.exists(fn):
        raise ValueError("%r doesn't exist" % (fn,))
    try:
        ret = reflect.namedAny(reflect.filenameToModuleName(fn))
    except (ValueError, AttributeError):
        # Couldn't find module.  The file 'fn' is not in PYTHONPATH
        return _importFromFile(fn)
    # ensure that the loaded module matches the file
    retFile = os.path.splitext(ret.__file__)[0] + '.py'
    # not all platforms (e.g. win32) have os.path.samefile
    same = getattr(os.path, 'samefile', samefile)
    if os.path.isfile(fn) and not same(fn, retFile):
        del sys.modules[ret.__name__]
        ret = _importFromFile(fn)
    return ret 
Example #23
Source File: service.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def makeService():
        def get(self):
            return namedAny(self.module).makeService
        return get, 
Example #24
Source File: service.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def options():
        def get(self):
            return namedAny(self.module).Options
        return get, 
Example #25
Source File: runner.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def loadDoctests(self, module):
        """
        Return a suite of tests for all the doctests defined in C{module}.

        @param module: A module object or a module name.
        """
        if isinstance(module, str):
            try:
                module = reflect.namedAny(module)
            except:
                return ErrorHolder(module, failure.Failure())
        if not inspect.ismodule(module):
            warnings.warn("trial only supports doctesting modules")
            return
        extraArgs = {}
        if sys.version_info > (2, 4):
            # Work around Python issue2604: DocTestCase.tearDown clobbers globs
            def saveGlobals(test):
                """
                Save C{test.globs} and replace it with a copy so that if
                necessary, the original will be available for the next test
                run.
                """
                test._savedGlobals = getattr(test, '_savedGlobals', test.globs)
                test.globs = test._savedGlobals.copy()
            extraArgs['setUp'] = saveGlobals
        return doctest.DocTestSuite(module, **extraArgs) 
Example #26
Source File: tap.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def opt_wsgi(self, name):
        """
        The FQPN of a WSGI application object to serve as the root resource of
        the webserver.
        """
        pool = threadpool.ThreadPool()
        reactor.callWhenRunning(pool.start)
        reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
        try:
            application = reflect.namedAny(name)
        except (AttributeError, ValueError):
            raise usage.UsageError("No such WSGI application: %r" % (name,))
        self['root'] = wsgi.WSGIResource(reactor, pool, application) 
Example #27
Source File: sim.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def _convertDistribution(cls, value):
        """
        Construct and return a new distribution object using the type and
        params specified by C{value}.
        """
        return namedAny(value['type'])(**value['params']) 
Example #28
Source File: test_migrate.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def pickleConfig(self, config, delegateTo):
        # from twistedcaldav.config import config as globalConfig
        # globalConfig._data = config._data
        swapAMP(self, namedAny(delegateTo)(config))
        return {} 
Example #29
Source File: test_migrate.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def createStore(self, delegateTo):
        """
        Create a store and pass it to the named delegate class.
        """
        swapAMP(self, namedAny(delegateTo)(SQLStoreBuilder.childStore()))
        return {} 
Example #30
Source File: service.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def makeService():
        def get(self):
            return namedAny(self.module).makeService
        return get,