當前位置: 首頁>>代碼示例>>Python>>正文


Python builtins.len方法代碼示例

本文整理匯總了Python中builtins.len方法的典型用法代碼示例。如果您正苦於以下問題:Python builtins.len方法的具體用法?Python builtins.len怎麽用?Python builtins.len使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在builtins的用法示例。


在下文中一共展示了builtins.len方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_modify_builtins_from_leaf_function

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def test_modify_builtins_from_leaf_function(self):
        # Verify that modifications made by leaf functions percolate up the
        # callstack.
        with swap_attr(builtins, "len", len):
            def bar():
                builtins.len = lambda x: 4

            def foo(modifier):
                l = []
                l.append(len(range(7)))
                modifier()
                l.append(len(range(7)))
                return l
            self.configure_func(foo, lambda: None)

            self.assertEqual(foo(bar), [7, 4]) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:18,代碼來源:test_dynamic.py

示例2: control_dependencies

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def control_dependencies(dependencies, graph=None):
    """
    Ensure that all `dependencies` are executed before any operations in this scope.

    Parameters
    ----------
    dependencies : list
        Sequence of operations to be evaluted before evaluating any operations defined in this
        scope.
    """
    # Add dependencies to the graph
    graph = Graph.get_active_graph(graph)
    graph.dependencies.extend(dependencies)
    yield
    # Remove dependencies from the graph
    del graph.dependencies[-len(dependencies):]


# pylint: disable=C0103 
開發者ID:spotify,項目名稱:pythonflow,代碼行數:21,代碼來源:core.py

示例3: print_mem

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def print_mem(self, base, num_elements, t="int", base_alias=""):
        if not base_alias:
            base_alias = f"0x{base:02x}"

        string = None
        if t == "str":
            string = get_string(base, self.engine.uc)
            t = "byte"
            num_elements = len(string)

        types = {
            "byte": ("B", 1),
            "int": ("<I", 4)
        }
        fmt, size = types[t]
        for i in range(num_elements):
            item, = struct.unpack(fmt, self.engine.uc.mem_read(base + i * size, size))
            print(f"{base_alias}+{i * 4} = 0x{item:02x}")

        if string is not None:
            print(f"String @0x{base:02x}: {string}") 
開發者ID:unipacker,項目名稱:unipacker,代碼行數:23,代碼來源:shell.py

示例4: do_aaa

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def do_aaa(self, args):
        """Analyze absolutely all: Show a collection of stats about the current sample"""
        print(f"{Fore.LIGHTRED_EX}File analysis:{Fore.RESET}")
        print_cols([
            ("YARA:", ", ".join(map(str, self.sample.yara_matches))),
            ("Chosen unpacker:", self.sample.unpacker.__class__.__name__),
            ("Allowed sections:", ', '.join(self.sample.unpacker.allowed_sections)),
            ("End of unpacking stub:",
             f"0x{self.sample.unpacker.endaddr:02x}" if self.sample.unpacker.endaddr != sys.maxsize else "unknown"),
            ("Section hopping detection:", "active" if self.sample.unpacker.section_hopping_control else "inactive"),
            ("Write+Exec detection:", "active" if self.sample.unpacker.write_execute_control else "inactive")
        ])
        print(f"\n{Fore.LIGHTRED_EX}PE stats:{Fore.RESET}")
        print_cols([
            ("Declared virtual memory size:", f"0x{self.sample.virtualmemorysize:02x}", "", ""),
            ("Actual loaded image size:", f"0x{len(self.sample.loaded_image):02x}", "", ""),
            ("Image base address:", f"0x{self.sample.BASE_ADDR:02x}", "", ""),
            ("Mapped stack space:", f"0x{self.engine.STACK_ADDR:02x}", "-",
             f"0x{self.engine.STACK_ADDR + self.engine.STACK_SIZE:02x}"),
            ("Mapped hook space:", f"0x{self.engine.HOOK_ADDR:02x}", "-", f"0x{self.engine.HOOK_ADDR + 0x1000:02x}")
        ])
        self.do_i("i")
        print(f"\n{Fore.LIGHTRED_EX}Register status:{Fore.RESET}")
        self.do_i("r") 
開發者ID:unipacker,項目名稱:unipacker,代碼行數:26,代碼來源:shell.py

示例5: count

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def count(iterable):
    '''Return the element count of ``iterable``.

    This is similar to the built-in :func:`len() <python:len>`, except that it
    can also handle any argument that supports iteration, including
    generators.
    '''
    try:
        return builtins.len(iterable)
    except TypeError:
        # Try to determine length by iterating over the iterable
        ret = 0
        for ret, _ in builtins.enumerate(iterable, start=1):
            pass

        return ret 
開發者ID:eth-cscs,項目名稱:reframe,代碼行數:18,代碼來源:sanity.py

示例6: listfunc

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def listfunc(func):
    def wrapper(*args):
        if builtins.len(args) == 1:
            if isinstance(args[0], list):
                try:
                    return func(args[0])
                except:
                    pass

            try:
                return func(list(iter(args[0])))
            except:
                pass

        return func(list(args))

    setattr(wrapper, "listfunc", True)
    return wrapper 
開發者ID:TuringApp,項目名稱:Turing,代碼行數:20,代碼來源:stats.py

示例7: test_cannot_change_globals_or_builtins_with_exec

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def test_cannot_change_globals_or_builtins_with_exec(self):
        def foo():
            return len([1, 2, 3])
        self.configure_func(foo)

        globals_dict = {"foo": foo}
        exec("x = foo()", globals_dict)
        self.assertEqual(globals_dict["x"], 3)

        # Note that this *doesn't* change the definition of len() seen by foo().
        builtins_dict = {"len": lambda x: 7}
        globals_dict = {"foo": foo, "__builtins__": builtins_dict,
                        "len": lambda x: 8}

        exec("x = foo()", globals_dict)
        self.assertEqual(globals_dict["x"], 3) 
開發者ID:ShikyoKira,項目名稱:Project-New-Reign---Nemesis-Main,代碼行數:18,代碼來源:test_dynamic.py

示例8: _get_conditional_content

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def _get_conditional_content(self, fname, spans, conditions, contents):
        out = []
        ieval = []
        peval = []
        multiline = (spans[0][0] != spans[-1][1])
        for condition, content, span in zip(conditions, contents, spans):
            try:
                cond = bool(self._evaluate(condition, fname, span[0]))
            except Exception as exc:
                msg = "exception occurred when evaluating '{0}'"\
                      .format(condition)
                raise FyppFatalError(msg, fname, span, exc)
            if cond:
                if self._linenums and not self._diverted and multiline:
                    out.append(linenumdir(span[1], fname))
                outcont, ievalcont, pevalcont = self._render(content)
                ieval += _shiftinds(ievalcont, len(out))
                peval += pevalcont
                out += outcont
                break
        if self._linenums and not self._diverted and multiline:
            out.append(linenumdir(spans[-1][1], fname))
        return out, ieval, peval 
開發者ID:aradi,項目名稱:fypp,代碼行數:25,代碼來源:fypp.py

示例9: __init__

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def __init__(self, maxlen=132, indent=4, method='smart', prefix='&',
                 suffix='&'):
        # Line length should be long enough that contintuation lines can host at
        # east one character apart of indentation and two continuation signs
        minmaxlen = indent + len(prefix) + len(suffix) + 1
        if maxlen < minmaxlen:
            msg = 'Maximal line length less than {0} when using an indentation'\
                  ' of {1}'.format(minmaxlen, indent)
            raise FyppFatalError(msg)
        self._maxlen = maxlen
        self._indent = indent
        self._prefix = ' ' * self._indent + prefix
        self._suffix = suffix
        if method not in ['brute', 'smart', 'simple']:
            raise FyppFatalError('invalid folding type')
        if method == 'brute':
            self._inherit_indent = False
            self._fold_position_finder = self._get_maximal_fold_pos
        elif method == 'simple':
            self._inherit_indent = True
            self._fold_position_finder = self._get_maximal_fold_pos
        elif method == 'smart':
            self._inherit_indent = True
            self._fold_position_finder = self._get_smart_fold_pos 
開發者ID:aradi,項目名稱:fypp,代碼行數:26,代碼來源:fypp.py

示例10: run_fypp

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def run_fypp():
    '''Run the Fypp command line tool.'''
    options = FyppOptions()
    optparser = get_option_parser()
    opts, leftover = optparser.parse_args(values=options)
    infile = leftover[0] if len(leftover) > 0 else '-'
    outfile = leftover[1] if len(leftover) > 1 else '-'
    try:
        tool = Fypp(opts)
        tool.process_file(infile, outfile)
    except FyppStopRequest as exc:
        sys.stderr.write(_formatted_exception(exc))
        sys.exit(USER_ERROR_EXIT_CODE)
    except FyppFatalError as exc:
        sys.stderr.write(_formatted_exception(exc))
        sys.exit(ERROR_EXIT_CODE) 
開發者ID:aradi,項目名稱:fypp,代碼行數:18,代碼來源:fypp.py

示例11: _get_callable_argspec_py2

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def _get_callable_argspec_py2(func):
    argspec = inspect.getargspec(func)
    varpos = argspec.varargs
    varkw = argspec.keywords
    args = argspec.args
    tuplearg = False
    for elem in args:
        tuplearg = tuplearg or isinstance(elem, list)
    if tuplearg:
        msg = 'tuple argument(s) found'
        raise FyppFatalError(msg)
    defaults = {}
    if argspec.defaults is not None:
        for ind, default in enumerate(argspec.defaults):
            iarg = len(args) - len(argspec.defaults) + ind
            defaults[args[iarg]] = default
    return args, defaults, varpos, varkw 
開發者ID:aradi,項目名稱:fypp,代碼行數:19,代碼來源:fypp.py

示例12: test_globals_shadow_builtins

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def test_globals_shadow_builtins(self):
        # Modify globals() to shadow an entry in builtins.
        def foo():
            return len([1, 2, 3])
        self.configure_func(foo)

        self.assertEqual(foo(), 3)
        with swap_item(globals(), "len", lambda x: 7):
            self.assertEqual(foo(), 7) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:11,代碼來源:test_dynamic.py

示例13: test_modify_builtins

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def test_modify_builtins(self):
        # Modify the builtins module directly.
        def foo():
            return len([1, 2, 3])
        self.configure_func(foo)

        self.assertEqual(foo(), 3)
        with swap_attr(builtins, "len", lambda x: 7):
            self.assertEqual(foo(), 7) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:11,代碼來源:test_dynamic.py

示例14: test_modify_builtins_while_generator_active

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def test_modify_builtins_while_generator_active(self):
        # Modify the builtins out from under a live generator.
        def foo():
            x = range(3)
            yield len(x)
            yield len(x)
        self.configure_func(foo)

        g = foo()
        self.assertEqual(next(g), 3)
        with swap_attr(builtins, "len", lambda x: 7):
            self.assertEqual(next(g), 7) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:14,代碼來源:test_dynamic.py

示例15: test_cannot_change_globals_or_builtins_with_eval

# 需要導入模塊: import builtins [as 別名]
# 或者: from builtins import len [as 別名]
def test_cannot_change_globals_or_builtins_with_eval(self):
        def foo():
            return len([1, 2, 3])
        self.configure_func(foo)

        # Note that this *doesn't* change the definition of len() seen by foo().
        builtins_dict = {"len": lambda x: 7}
        globals_dict = {"foo": foo, "__builtins__": builtins_dict,
                        "len": lambda x: 8}
        self.assertEqual(eval("foo()", globals_dict), 3)

        self.assertEqual(eval("foo()", {"foo": foo}), 3) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:14,代碼來源:test_dynamic.py


注:本文中的builtins.len方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。