当前位置: 首页>>代码示例>>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;未经允许,请勿转载。