当前位置: 首页>>代码示例>>Python>>正文


Python repr函数代码示例

本文整理汇总了Python中repr函数的典型用法代码示例。如果您正苦于以下问题:Python repr函数的具体用法?Python repr怎么用?Python repr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了repr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_syntactic

    def test_syntactic(self):
        sentences = list(SyntacticExtractor(
            [{'bio': u'this is part a1, and this is part a2', 'url': 'www.example.org', 'name': 'abc def'}],
            'bio', 'sentences', 'en', {'be': ['is', 'are']}, self.match_base_form
        ).extract(1))

        self.assertEqual(len(sentences), 2)

        missing_parts = {'a1', 'a2'}
        for sentence in sentences:
            self.assertIn('url', sentence)
            self.assertIn('text', sentence)
            self.assertIn('lu', sentence)
            self.assertEqual(sentence['lu'], 'be')

            for p in missing_parts:
                if p in sentence['text']:
                    self.assertEqual(sentence['text'], 'this is part ' + p)
                    missing_parts.remove(p)
                    break
            else:
                self.fail('Extracted unexpected sentence: %s' % repr(sentence))

        if missing_parts:
            self.fail('Did not find parts: %s' % repr(missing_parts))
开发者ID:Wikidata,项目名称:StrepHit,代码行数:25,代码来源:test_extraction.py

示例2: test_add_filter

    def test_add_filter(self):
        self.assertEqual(len(self.bsq.query_filter), 0)

        self.bsq.add_filter(SQ(foo="bar"))
        self.assertEqual(len(self.bsq.query_filter), 1)

        self.bsq.add_filter(SQ(foo__lt="10"))

        self.bsq.add_filter(~SQ(claris="moof"))

        self.bsq.add_filter(SQ(claris="moof"), use_or=True)

        self.assertEqual(
            repr(self.bsq.query_filter),
            "<SQ: OR ((foo__content=bar AND foo__lt=10 AND NOT (claris__content=moof)) OR claris__content=moof)>",
        )

        self.bsq.add_filter(SQ(claris="moof"))

        self.assertEqual(
            repr(self.bsq.query_filter),
            "<SQ: AND (((foo__content=bar AND foo__lt=10 AND NOT (claris__content=moof)) OR claris__content=moof) AND claris__content=moof)>",
        )

        self.bsq.add_filter(SQ(claris="wtf mate"))

        self.assertEqual(
            repr(self.bsq.query_filter),
            "<SQ: AND (((foo__content=bar AND foo__lt=10 AND NOT (claris__content=moof)) OR claris__content=moof) AND claris__content=moof AND claris__content=wtf mate)>",
        )
开发者ID:antonyr,项目名称:django-haystack,代码行数:30,代码来源:test_query.py

示例3: iterate_node

def iterate_node(arg):
    ctx, address, backend_id, ranges = arg
    elog = elliptics.Logger(ctx.log_file, int(ctx.log_level))
    stats = ctx.stats["iterate"][str(address)][str(backend_id)]
    stats.timer('process', 'started')
    log.info("Running iterator on node: {0}/{1}".format(address, backend_id))
    log.debug("Ranges:")
    for range in ranges:
        log.debug(repr(range))
    stats.timer('process', 'iterate')

    node_id = ctx.routes.get_address_backend_route_id(address, backend_id)

    node = elliptics_create_node(address=address,
                                 elog=elog,
                                 wait_timeout=ctx.wait_timeout,
                                 net_thread_num=4,
                                 io_thread_num=1)

    try:
        flags = elliptics.iterator_flags.key_range
        timestamp_range = ctx.timestamp.to_etime(), Time.time_max().to_etime()
        if ctx.no_meta:
            flags |= elliptics.iterator_flags.no_meta
        else:
            flags |= elliptics.iterator_flags.ts_range

        log.debug("Running iterator on node: {0}/{1}".format(address, backend_id))
        results, results_len = Iterator.iterate_with_stats(
            node=node,
            eid=node_id,
            timestamp_range=timestamp_range,
            key_ranges=ranges,
            tmp_dir=ctx.tmp_dir,
            address=address,
            backend_id=backend_id,
            group_id=node_id.group_id,
            batch_size=ctx.batch_size,
            stats=stats,
            flags=flags,
            leave_file=True,
            separately=True)
        if results is None or results_len == 0:
            return None

    except Exception as e:
        log.error("Iteration failed for node {0}/{1}: {2}, traceback: {3}"
                  .format(address, backend_id, repr(e), traceback.format_exc()))
        return None

    log.debug("Iterator for node {0}/{1} obtained: {2} record(s)"
              .format(address, backend_id, results_len))

    stats.timer('process', 'sort')
    for range_id in results:
        results[range_id].sort()

    stats.timer('process', 'finished')
    return [(range_id, container.filename, container.address, container.backend_id, container.group_id)
            for range_id, container in results.items()]
开发者ID:iderikon,项目名称:elliptics,代码行数:60,代码来源:dc.py

示例4: _writer_coro

 def _writer_coro(self):
     self.logger.debug("Starting writer coro")
     while self._running:
         try:
             self._writer_ready.set()
             packet = yield from asyncio.wait_for(self.outgoing_queue.get(), 5)
             yield from packet.to_stream(self.session.writer)
             self.logger.debug(" -out-> " + repr(packet))
             yield from self.session.writer.drain()
             self.packet_sent.send(packet)
         except asyncio.TimeoutError as ce:
             self.logger.debug("Output queue get timeout")
         except Exception as e:
             self.logger.warn("Unhandled exception in writer coro: %s" % e)
             break
     self.logger.debug("Writer coro stopping")
     # Flush queue before stopping
     if not self.outgoing_queue.empty():
         while True:
             try:
                 packet = self.outgoing_queue.get_nowait()
                 yield from packet.to_stream(self.session.writer)
                 self.logger.debug(" -out-> " + repr(packet))
             except asyncio.QueueEmpty:
                 break
             except Exception as e:
                 self.logger.warn("Unhandled exception in writer coro: %s" % e)
     self.logger.debug("Writer coro stopped")
开发者ID:gitter-badger,项目名称:hbmqtt,代码行数:28,代码来源:protocol.py

示例5: _http_request

    def _http_request(self, method, url, headers, body,
                      ignore_result_body=False):
        """Perform an HTTP request against the server.

        method: the HTTP method to use
        url: the URL to request (not including server portion)
        headers: headers for the request
        body: body to send with the request
        ignore_result_body: the body of the result will be ignored

        Returns: a http_client response object
        """
        if self.auth_token:
            headers.setdefault('x-auth-token', self.auth_token)

        LOG.debug('Request: %(method)s http://%(server)s:%(port)s'
                  '%(url)s with headers %(headers)s',
                  {'method': method,
                   'server': self.conn.host,
                   'port': self.conn.port,
                   'url': url,
                   'headers': repr(headers)})
        self.conn.request(method, url, body, headers)

        response = self.conn.getresponse()
        headers = self._header_list_to_dict(response.getheaders())
        code = response.status
        code_description = http_client.responses[code]
        LOG.debug('Response: %(code)s %(status)s %(headers)s',
                  {'code': code,
                   'status': code_description,
                   'headers': repr(headers)})

        if code == 400:
            raise exc.HTTPBadRequest(
                explanation=response.read())

        if code == 500:
            raise exc.HTTPInternalServerError(
                explanation=response.read())

        if code == 401:
            raise exc.HTTPUnauthorized(
                explanation=response.read())

        if code == 403:
            raise exc.HTTPForbidden(
                explanation=response.read())

        if code == 409:
            raise exc.HTTPConflict(
                explanation=response.read())

        if ignore_result_body:
            # NOTE: because we are pipelining requests through a single HTTP
            # connection, http_client requires that we read the response body
            # before we can make another request. If the caller knows they
            # don't care about the body, they can ask us to do that for them.
            response.read()
        return response
开发者ID:froyobin,项目名称:xmonitor,代码行数:60,代码来源:replicator.py

示例6: test_repr

def test_repr():
    d = da.ones((4, 4), chunks=(2, 2))
    assert d.name[:5] in repr(d)
    assert str(d.shape) in repr(d)
    assert str(d._dtype) in repr(d)
    d = da.ones((4000, 4), chunks=(4, 2))
    assert len(str(d)) < 1000
开发者ID:hc10024,项目名称:dask,代码行数:7,代码来源:test_array_core.py

示例7: test_body

def test_body():
    """Check code blocks."""
    body_tuple = (ast.IntLiteral(10), ast.IntLiteral(20))
    body = ast.Body(body_tuple)
    assert body['statements'] is body_tuple
    assert str(body) == '  10\n  20'
    assert repr(body) == 'Body({body_tuple})'.format(body_tuple=repr(body_tuple))
开发者ID:vslutov,项目名称:llb3d,代码行数:7,代码来源:test_ast.py

示例8: gexpect

    def gexpect(self, tag):
        log.debug('GAME_EXPECT: %s', repr(tag))
        l = self.gdqueue
        e = self.gdevent
        while True:
            for i in xrange(len(l)):
                d = l.popleft()
                if isinstance(d, EndpointDied):
                    raise d

                elif d[0] == tag:
                    log.debug('GAME_READ: %s', repr(d))
                    self.usergdhistory.append((self.player_index, d[0], d[1]))
                    return d[1]

                else:
                    d.scan_count += 1
                    if d.scan_count >= 15:
                        log.debug('Dropped gamedata: %s' % d)
                    else:
                        log.debug('GAME_DATA_MISS: %s', repr(d))
                        log.debug('EXPECTS: %s' % tag)
                        l.append(d)
            e.clear()
            e.wait()
开发者ID:CoolCloud,项目名称:thbattle,代码行数:25,代码来源:client_endpoint.py

示例9: test_ViewInventory___deepcopy___01

def test_ViewInventory___deepcopy___01():
    
    inventory_1 = idetools.ViewInventory()
    inventory_2 = copy.deepcopy(inventory_1)

    assert inventory_1 == inventory_2
    assert repr(inventory_1) == repr(inventory_2)
开发者ID:jefftrevino,项目名称:abjad,代码行数:7,代码来源:test_ViewInventory___deepcopy__.py

示例10: test_categorical_series_repr_ordered

    def test_categorical_series_repr_ordered(self):
        s = Series(Categorical([1, 2, 3], ordered=True))
        exp = """0    1
1    2
2    3
dtype: category
Categories (3, int64): [1 < 2 < 3]"""

        assert repr(s) == exp

        s = Series(Categorical(np.arange(10), ordered=True))
        exp = """0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: category
Categories (10, int64): [0 < 1 < 2 < 3 ... 6 < 7 < 8 < 9]"""

        assert repr(s) == exp
开发者ID:TomAugspurger,项目名称:pandas,代码行数:25,代码来源:test_repr.py

示例11: test_categorical_series_repr

    def test_categorical_series_repr(self):
        s = Series(Categorical([1, 2, 3]))
        exp = """0    1
1    2
2    3
dtype: category
Categories (3, int64): [1, 2, 3]"""

        assert repr(s) == exp

        s = Series(Categorical(np.arange(10)))
        exp = """0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: category
Categories (10, int64): [0, 1, 2, 3, ..., 6, 7, 8, 9]"""

        assert repr(s) == exp
开发者ID:TomAugspurger,项目名称:pandas,代码行数:25,代码来源:test_repr.py

示例12: test_categorical_repr_unicode

    def test_categorical_repr_unicode(self):
        # GH#21002 if len(index) > 60, sys.getdefaultencoding()=='ascii',
        # and we are working in PY2, then rendering a Categorical could raise
        # UnicodeDecodeError by trying to decode when it shouldn't

        class County(StringMixin):
            name = u'San Sebastián'
            state = u'PR'

            def __unicode__(self):
                return self.name + u', ' + self.state

        cat = pd.Categorical([County() for n in range(61)])
        idx = pd.Index(cat)
        ser = idx.to_series()

        if compat.PY3:
            # no reloading of sys, just check that the default (utf8) works
            # as expected
            repr(ser)
            str(ser)

        else:
            # set sys.defaultencoding to ascii, then change it back after
            # the test
            with tm.set_defaultencoding('ascii'):
                repr(ser)
                str(ser)
开发者ID:TomAugspurger,项目名称:pandas,代码行数:28,代码来源:test_repr.py

示例13: test_various_ops

    def test_various_ops(self):
        # This takes about n/3 seconds to run (about n/3 clumps of tasks,
        # times about 1 second per clump).
        NUMTASKS = 10

        # no more than 3 of the 10 can run at once
        sema = threading.BoundedSemaphore(value=3)
        mutex = threading.RLock()
        numrunning = Counter()

        threads = []

        for i in range(NUMTASKS):
            t = TestThread("<thread %d>" % i, self, sema, mutex, numrunning)
            threads.append(t)
            self.assertEqual(t.ident, None)
            self.assertTrue(re.match("<TestThread\(.*, initial\)>", repr(t)))
            t.start()

        if verbose:
            print("waiting for all tasks to complete")
        for t in threads:
            t.join(NUMTASKS)
            self.assertTrue(not t.is_alive())
            self.assertNotEqual(t.ident, 0)
            self.assertFalse(t.ident is None)
            self.assertTrue(re.match("<TestThread\(.*, stopped -?\d+\)>", repr(t)))
        if verbose:
            print("all tasks done")
        self.assertEqual(numrunning.get(), 0)
开发者ID:pykomke,项目名称:Kurz_Python_KE,代码行数:30,代码来源:test_threading.py

示例14: edit_tagged_sel

    def edit_tagged_sel(self, tag_sel_idx, *, note=None):
        tagged_sel = self.store[tag_sel_idx]
        old_note = tagged_sel.note
        tagged_sel.note = note
        print("Updated note: %s -> %s" % (repr(old_note), repr(note)))

        self.store.save()
开发者ID:jheiv,项目名称:pep3156revisited,代码行数:7,代码来源:tagger.py

示例15: __repr__

 def __repr__(self):
     r = u"[%s ->\n %s\n source=%s strength=%.2f votes=%d)]" % (
         repr(self.input).decode("utf8"),
         repr(self.output).decode("utf8"),
         self.data_source.name, self.strength, self.votes
     )
     return r.encode("utf8")
开发者ID:NYPL-Simplified,项目名称:server_core,代码行数:7,代码来源:identifier.py


注:本文中的repr函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。